Android test in kotlin of realm

六月ゝ 毕业季﹏ 提交于 2019-12-24 04:24:06

问题


How can be done a simple test of a realm database in Android implementing the test in Kotlin?

I attempted to adapt a fragment from java realm test on github to kotlin and got the next code:

import io.realm.Realm 
import io.realm.log.RealmLog 
import org.hamcrest.CoreMatchers 
import org.junit.Assert

import org.junit.Test import org.junit.Before import org.junit.Rule
import org.mockito.Mockito.`when` 
import org.powermock.api.mockito.PowerMockito 
import org.powermock.modules.junit4.rule.PowerMockRule

class DBTest {

    @Rule
    var rule = PowerMockRule()
    lateinit internal var mockRealm: Realm

    @Before
    fun setup() {
        PowerMockito.mockStatic(RealmLog::class.java)
        PowerMockito.mockStatic(Realm::class.java)

        val mockRealm = PowerMockito.mock(Realm::class.java)

        `when`(Realm.getDefaultInstance()).thenReturn(mockRealm)

        this.mockRealm = mockRealm
    }

    @Test
    fun shouldBeAbleToGetDefaultInstance() {
        Assert.assertThat(Realm.getDefaultInstance(), CoreMatchers.`is`(mockRealm))
    }

}

But when I execute the test I get:

org.junit.internal.runners.rules.ValidationError: The @Rule 'rule' must be public.

回答1:


You can make the getter of the rule public like so:

@get: Rule
var rule = PowerMockRule()

Or you can mark it as a Java style field with the @JvmField annotation:

@JvmField @Rule
var rule = PowerMockRule()

You can find more details in this answer: https://stackoverflow.com/a/32827600/4465208

Ps. You should also consider making it a val if you don't intend on changing its value anywhere.




回答2:


Realm java 4.1.0 has been released and most problem of Realm with Kotlin has resolved! . You can test my sample project to see how you must config project or create classes. My sample is for testing module in Realm object Server with kotlin.



来源:https://stackoverflow.com/questions/42528039/android-test-in-kotlin-of-realm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!