JUnit frameworks and runners often create separate instances of the test class for each method call. It looks like that's what JUnitParams does - you can see that using the following test:
@RunWith(JUnitParamsRunner.class)
public class JUnitParamsTest {
@Test
@Parameters
public void test(JUnitParamsTest param) {
Assert.assertNotNull(param);
Assert.assertNotSame(this, param);
}
Object[] parametersForTest() {
return new Object[]{this};
}
}
So the problem with your example above is that the myList
field being set by parametersForTest
is a member of a different object from the one that test(List)
is being called on.
How to fix
Well, I guess the key question is, what are you trying to achieve here? The whole point of JUnitParams is that parameters are injected into the test methods, so you don't have to use fields. It seems to me that modifying field values inside the parametersForTest()
method is outside of intended usage, and I can't really see why you'd want to do this.
One quick and dirty fix would be to make myList
static, which should work so long as your test class isn't accessed by multiple threads concurrently (some unit-test environments do run multi-threaded so there is a risk here).
A better solution would be to redesign your tests so that you're not modifying fields from inside of parameter-generating methods. The example you've given doesn't appear to be attempting to test anything other than JUnitParams itself, so I can't help you determine what a good design would be, as I son't know what you're trying to achieve. Are you saying you want several test methods to share a single Mockito mock? If so, why? I'm not sure Mockito would support this (I haven't tried). Unit tests are generally supposed to be isolated from each other, so the recommended action would be to create a new mock each time.