领域 - 当这些对象是在测试 Class @Before 方法上创建时,无法查询 Activity/Fragment 内的对象
Realm - Cannot query objects inside an Activity/Fragment when these Objects were created on the Test Class @Before method
当尝试在 JUnity4 测试用例的 @Before
方法中创建模拟数据时,我无法在正在测试的 Activity 中使用 Realm 查询创建的数据。
问题是 JUnity 测试在 @Before
方法 运行 之前启动 activity。
这意味着在 Activity 启动时,在测试用例上创建的数据不可用。
解决方案:
告诉测试 运行ner 在测试 运行.
之前不要启动 Activity
@Rule
public ActivityTestRule<MainActivity> activityRule =
new ActivityTestRule<>(MainActivity.class, false, false); // NOTE THE FALSES
创建所需数据后手动启动activity。
@Before
public void before() {
// This must be the same config as the one being used by your app in the test.
final RealmConfiguration configuration = new RealmConfiguration.Builder(InstrumentationRegistry.getTargetContext())
.name(TaskerApplication.REALM_FILE)
.deleteRealmIfMigrationNeeded()
.schemaVersion(0)
.build();
realm = Realm.getInstance(configuration);
realm.beginTransaction();
createdObject = realm.copyToRealm(new AnyRealmObject());
realm.commitTransaction();
// Launch the Activity manually
activityRule.launchActivity(new Intent(Intent.ACTION_MAIN));
// Object will be available when queried from the Activity.
}
当尝试在 JUnity4 测试用例的 @Before
方法中创建模拟数据时,我无法在正在测试的 Activity 中使用 Realm 查询创建的数据。
问题是 JUnity 测试在 @Before
方法 运行 之前启动 activity。
这意味着在 Activity 启动时,在测试用例上创建的数据不可用。
解决方案:
告诉测试 运行ner 在测试 运行.
之前不要启动 Activity@Rule public ActivityTestRule<MainActivity> activityRule = new ActivityTestRule<>(MainActivity.class, false, false); // NOTE THE FALSES
创建所需数据后手动启动activity。
@Before public void before() { // This must be the same config as the one being used by your app in the test. final RealmConfiguration configuration = new RealmConfiguration.Builder(InstrumentationRegistry.getTargetContext()) .name(TaskerApplication.REALM_FILE) .deleteRealmIfMigrationNeeded() .schemaVersion(0) .build(); realm = Realm.getInstance(configuration); realm.beginTransaction(); createdObject = realm.copyToRealm(new AnyRealmObject()); realm.commitTransaction(); // Launch the Activity manually activityRule.launchActivity(new Intent(Intent.ACTION_MAIN)); // Object will be available when queried from the Activity. }