Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: IllegalAccessException: Class BlockJUnit4ClassRunner can not access a member of class Foo with modifiers “private”

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?

like image 381
vvbYWf0ugJOGNA3ACVxp Avatar asked Apr 05 '19 01:04

vvbYWf0ugJOGNA3ACVxp


1 Answers

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;
}
like image 142
vvbYWf0ugJOGNA3ACVxp Avatar answered Oct 17 '22 00:10

vvbYWf0ugJOGNA3ACVxp