android – 从Espresso中的错误线程访问Realm

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

我的对象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 access from incorrect thread. Realm objects can only be accessed on the thread they were created

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

我觉得有趣的solutions之一,创建一个假的init领域.

解决方法:

要从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
        }
    });
}
上一篇:android – 为什么/何时使用realm.beginTransaction?由于有executeTransaction和executeTransactionAsync


下一篇:java – Realm android,似乎没有应用RealmTransformer