adebasi adebasi - 1 month ago 5
Java Question

Why are field variables null after setting them in JUnitParams method?

I am writing a test class using

JUnitParams
and
Mockito
. I want to use a
Mockito mock
as
parameter
. In my test I have about ten mocks and I want to pass only one mock to define a special behaviour for it.

I reproduced the problem in a simple example.

My problem: I initialize the variable
myList
in the method
parametersForTest
, but when I debug into the
test
method
myList
is null, but
param
is my desired mock.

@RunWith(JUnitParamsRunner.class)
public class MockitoJUnitParamsTest {

private List myList;

@Test
@Parameters
public void test(List param) {
assertThat(param).isEqualTo(this.myList);
}

public Object[] parametersForTest() {
myList = Mockito.mock(List.class);
return new Object[]{myList};
}
}


I use


  • JUnitParams version 1.0.5

  • JUnit version 4.12

  • Mockito version 1.10.19



Why is myList null and how can I fix that?

Answer

The instance of the MockitoJUnitParamsTest class running parametersForTest() method is not the same running test(). This is because Junit will create a different instance for each test method. In your case , making myList static

private static List myList;

can solve the problem partially, but It may fail if the tests run in parallel.