当尝试在 JUnity4 测试用例的 @Before
方法中创建模拟数据时,我无法在被测试的 Activity 中使用 Realm 查询创建的数据。
最佳答案
问题是 JUnity 测试在 @Before
方法运行之前启动 Activity 。
这意味着在 Activity 启动时在测试用例上创建的数据不可用。
解决方法:
告诉测试运行器在测试运行之前不要启动 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. }
关于android - Realm - 当在测试类 @Before 方法上创建这些对象时,无法查询 Activity/fragment 内的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34050308/