2

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.
gilcu2
  • 343
  • 3
  • 13

2 Answers2

6

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.

Community
  • 1
  • 1
zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • Thanks, "@get Rule" fixed the problem. Now I am getting java.lang.NoClassDefFoundError: org/mockito/cglib/proxy/Enhancer but this is another question. – gilcu2 Mar 01 '17 at 11:32
-1

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.

Saeed
  • 101
  • 1
  • 1
  • 12