gpt4 book ai didi

android - Espresso 中错误线程的 Realm 访问

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:35:22 25 4
gpt4 key购买 nike

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

我的 object Realm 的代码 fragment :

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

那么我如何才能在我的测试中正确地初始化我的 Realm ?

solutions 之一我发现有趣的是,创建一个假的初始化 Realm 。

最佳答案

要从 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 - Espresso 中错误线程的 Realm 访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44494846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com