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)?
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With