Realm access from incorrect thread in Espresso Realm access from incorrect thread in Espresso multithreading multithreading

Realm access from incorrect thread in Espresso


To manipulate the UI thread's Realm instance from your UI tests, you need to initialize the Realm instance on the UI thread using instrumentation.runOnMainSync(() -> {...});.

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


What i do.I just added next function in my AppTools, which check package with tests:

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

Then modifed init of Realm:

 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)    }}