领域从Espresso中的错误线程访问

时间:2017-06-12 08:34:43

标签: android multithreading realm kotlin android-espresso

在每次espresso测试之前,我都有一个注释@Before,我在其中初始化RealmManager.realm

我的object Realm的代码段:

init {
    Realm.init(SaiApplication.context)
    val builder = RealmConfiguration.Builder().schemaVersion(SCHEMA_VERSION)
    builder.migration(runMigrations())
    if (!BuildConfig.DEBUG) builder.encryptionKey(getOrCreateDatabaseKey())
    if (SaiApplication.inMemoryDatabase) builder.inMemory()
    Realm.setDefaultConfiguration(builder.build())
    try {
        errorOccurred = false
        realm = Realm.getDefaultInstance()
    } catch (e: Exception) {
        errorOccurred = true
        realm = Realm.getInstance(RealmConfiguration.Builder()
                .schemaVersion(SCHEMA_VERSION).name(errorDbName).build())
        e.log()
        deleteRealmFile(realm.configuration.realmDirectory)
    }
}

但是当我运行测试时,我会收到下一个错误:

  

Realm从错误的线程访问。 Realm对象只能在创建它们的线程上访问

那么我如何在测试中正确地启动我的领域呢?

我觉得有趣的solutions之一,创造了一个虚假的初始领域。

2 个答案:

答案 0 :(得分:4)

要从UI测试中操作UI线程的Realm实例,您需要使用instrumentation.runOnMainSync(() -> {...});在UI线程上初始化Realm实例。

@Before
public void setup() {
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    instrumentation.runOnMainSync(new Runnable() {
        @Override
        public void run() {
           // setup UI thread Realm instance configuration
        }
    });
}

答案 1 :(得分:1)

我做什么。 我刚刚在我的AppTools中添加了下一个函数,它通过测试检查包:

fun isTestsSuite() = AppResources.appContext?.classLoader.toString().contains("tests")

然后修改了Realm的init:

 init {
    Realm.init(AppResources.appContext)
    val builder = RealmConfiguration.Builder().schemaVersion(SCHEMA_VERSION)
    builder.migration(runMigrations())
    if (!isTestsSuite()) builder.encryptionKey(getOrCreateDatabaseKey()) else builder.inMemory()
    Realm.setDefaultConfiguration(builder.build())
    try {
        errorOccurred = false
        realm = Realm.getDefaultInstance()
    } catch (e: Exception) {
        errorOccurred = true
        realm = Realm.getInstance(RealmConfiguration.Builder()
                .schemaVersion(SCHEMA_VERSION).name(errorDbName).build())
        e.log()
        deleteRealmFile(realm.configuration.realmDirectory)
    }
}