Using Kotlin with Junit 4 I get the following exception for Parameter field injection:
java.lang.IllegalAccessException: Class org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParameters can not access a member of class MyTestClass with modifiers "private"
Here's the code:
@RunWith(Parameterized::class)
class MyTestClass {
@Rule
@JvmField
val mockitoRule: MockitoRule = MockitoJUnit.rule()
companion object {
@Parameters(name = "{0}")
@JvmStatic
fun testData() = listOf(
arrayOf(1, 1),
arrayOf(2, 2),
arrayOf(3, 3)
)
}
@Parameter
var input: Int = 0 // Public
@Parameter(1)
var expected: Int = 0 // Public
@Test
fun foo() {
assertEquals(expected, input)
}
}
Any ideas?
Tl;dr: Adding @JvmField to both fields solved the problem. Like so:
@JvmField
@Parameter
var input: Int = 0
@JvmField
@Parameter(1)
var expected: Int = 0
Explanation: By default, Kotlin will make the fields private and generate getters/setters as can be seen from the decompiled java code below, as a result JUnit won't be able to read the private fields hence the message: can not access a member of class MyTestClass with modifiers "private"
@Parameter
private int input;
@Parameter(1)
private int expected;
public final int getInput() {
return this.input;
}
public final void setInput(int var1) {
this.input = var1;
}
public final int getExpected() {
return this.expected;
}
public final void setExpected(int var1) {
this.expected = var1;
}
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