I have a fairly simple save()
method to persist a RealmModel
, after saving realm.close()
is called because the database is no longer needed.
The problem: The actual close()
method is called although Realm is mocked using mockito. This causes an exception:
IllegalStateException: Realm access from incorrect thread. Realm instance can only be closed on the thread it was created.
Is mockito not able to mock Realm? I don't want to include PowerMock just for testing this case :D
Tested using realm-gradle-plugin
5.0.0
The tested class
import io.realm.Realm
import io.realm.RealmModel
class TestedClass {
fun save(realm: Realm, objectToBeSaved: RealmModel) {
// Persist your data in a transaction
realm.executeTransaction {
// Using executeTransaction with a lambda reduces code size
// and makes it impossible to forget to commit the transaction.
it.copyToRealm(objectToBeSaved)
}
// Close database after saving (this causes the exception)
realm.close()
}
}
The Unit Test
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
@Test
fun save() {
val testedClass = TestedClass()
val mockRealm: Realm = mock()
val objectToBeSaved: RealmModel = mock()
testedClass.save(mockRealm, objectToBeSaved) // this causes the exception
verify(mockRealm).executeTransaction(any())
verify(mockRealm).copyToRealm(objectToBeSaved)
verify(mockRealm).close()
}