Search code examples
unit-testingkotlin

Test in Kotlin cannot access protected method


I want to test class B:

class B : A {
    override fun init() {
        // do work here
    }
}

class A {
    protected fun init() { } // will be called by internal logic
}

and in Java there is no problem to call: b.init() within test method (test class is in the same package as test subject), but in Kotlin compiler complains:

Cannot access 'init': it is protected in 'B'

@Test
fun `checks init`() {
    val b = B()
    b.init()
    // assert work done
}

Why isn't it working? How can this be workaround (I want to avoid making method public)?


Solution

  • Since Kotlin reduce visibility on protected (in compare to Java) by not allowing package access, the best option I could find is to workaround with reflection (since this is for testing I see no reason why not)

    private fun invokeHiddenMethod(name: String) {
        val method = sut.javaClass.getDeclaredMethod(name)
        method.isAccessible = true
        method.invoke(testSubject)
    }