Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 969
Kamil Seweryn Avatar asked Jan 15 '17 16:01

Kamil Seweryn


People also ask

Can you test a protected method?

So yes, you would test private and protected methods if you felt they needed to be tested for you to answer Yes to the question.

Can we override protected method in Kotlin?

In Kotlin if you override a protected member and do not specify the visibility explicitly, the overriding member will also have protected visibility. In Java the visibility is according to the modifier and the default is still public .

How does kotlin test private methods?

You can't directly test private methods, and you can't make a method private any other way than the keyword private . Either make them internal or only test public API.


1 Answers

protected in Java is not the same as in Kotlin.

In Java, everything in the same package can access a protected method. See In Java, difference between default, public, protected, and private

In Kotlin, protected means that you can only access it in the same class or any subclass of it. See Visibility Modifiers - Kotlin

The only possible way is to use the internal modifier and make the method visible to your tests in the same module.

like image 167
D3xter Avatar answered Sep 23 '22 01:09

D3xter