Realm is generally useful, although it's awkward to handle.
As a premise, I found it awkward to handle mainly when using Realm as a simple DB. Especially compared to the Swift version, it seems to be difficult to handle.
Realm depends on android, so I have to run it on Android Test. In that case, you can use Robolectric, but it seems that Realm is not yet supported (https://github.com/realm/realm-java/issues/904).
That is, it takes a long time to run, which makes testing uncomfortable.
Of course, it can work with PowerMock, but I want to verify that insert, update, select is working properly in realm with a test targeting Dao. (In layers other than Dao, Dao is mocked, so there is no problem.)
In Official Samples, PowerMock is still available. I am using.
Currently, there is no fundamental solution, it seems that you can only test if the mock is calling the method correctly.
It's natural to open and close a resource, but when I access a property with the intention of putting it in an entity, it crashes (`` This Realm instance has already been closed```. Java Realm is a specification that cannot be accessed after closing a resource.
To avoid that, you have to handle everything within the transaction. If you want to complete it with Dao only, you need to copy it to an instance not managed by realm as follows.
fun find(): AuthEntity? {
var result: AuthEntity? = null
Realm.getDefaultInstance().use { realm ->
val entity = realm.where(AuthEntity::class.java).findFirst()
if (entity != null) {
result = realm.copyFromRealm(entity)
}
}
return result
}
Realm is generally configured to be instantiated with onCreate () `` `and closed with
onDestroy () `` ([Official Document](https://realm.io/). docs / java / latest /) also seems to be "closed with
ʻonDestory ()
``).
But you don't want the Activity to depend on the Dao element, and you don't want the ViewModel to depend on the Realm, for example in the MVVM. So, I think I will create a class that wraps Realm and implement it to eliminate the dependency. However, it is exaggerated to be aware of transactions without depending on Realm even for simple acquisition processing.
Therefore, I think there is a decision / solution to write the above code. However, this process seems to be costly in memory and processing time.
When using with Kotlin, you have to put a default value in the argument due to this constraint. If you use kotlin-noarg Plugin, the default constructor will be generated automatically, but in the case of Realm, it could not be built because it was played in the pre-verification. Corresponding source locationis.
So even if you don't need the default values, you would write a class like this.
@RealmClass
data class SampleEntity(
@PrimaryKey
@SerializedName("id")
var id: Int = 0,
@SerializedName("sample")
var sample: String = ""
) : RealmModel
Recommended Posts