Accessing the Realm from the Wrong Thread in Espresso
Before every espresso test, I have an annotation @Before
where I initialize mine RealmManager.realm
.
Snippet of my code 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)
}
}
But when I run my tests, I get the following error:
Accessing the Realm from the wrong stream. Realm objects can only be accessed on a stream that was created
So how can I properly initialize my realm in my tests?
One solution I found interesting is creating a fake init area.
source to share
What am I doing. I just added the following function to my AppTools that check the package with tests:
fun isTestsSuite() = AppResources.appContext?.classLoader.toString().contains("tests")
Then the modified init 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)
}
}
source to share
To manipulate the Realm UI instance from your UI tests, you need to initialize the Realm instance on the UI thread using instrumentation.runOnMainSync(() -> {...});
.
@Before
public void setup() {
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
instrumentation.runOnMainSync(new Runnable() {
@Override
public void run() {
// setup UI thread Realm instance configuration
}
});
}
source to share