This follows on from this question: where I am asked to start a new question.
The problem is that I just don't know enough about JUnit Rule
, or what's going on here with Runners
and the like, to crack the problem in the way alluded to by Jeff Bowman.
In your later comments, I figured out the gap: You need to use Mockito as a Rule and Parameterized as a Runner, not the other way around.
The reason is that the Runner is responsible for reporting the number of tests, and Parameterized manipulates the number of tests based on the number of test methods and the number of parameterized inputs, so it's really important for Parameterized to be a part of the Runner process. By contrast, the use of a Mockito runner or rule is simply to encapsulate the @Before
and @After
methods that initialize Mockito annotations and validate Mockito usage, which can be done very easily as a @Rule
that works adjacent to other @Rule
instances--to the point that the MockitoJUnitRunner is very nearly deprecated.
To crib directly from the JUnit4 Parameterized Test doc page and MockitoRule doc page:
@RunWith(Parameterized.class)
public class YourComponentTest {
@Rule public MockitoRule rule = MockitoJUnit.rule();
@Mock YourDep mockYourDep;
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 }
});
}
private int fInput;
private int fExpected;
public YourComponentTest(int input, int expected) {
fInput = input;
fExpected = expected;
}
@Test
public void test() {
// As you may surmise, this is not a very realistic example of Mockito's use.
when(mockYourDep.calculate(fInput)).thenReturn(fExpected);
YourComponent yourComponent = new YourComponent(mockYourDep);
assertEquals(fExpected, yourComponent.compute(fInput));
}
}
来源:https://stackoverflow.com/questions/40793464/parameterized-testing-with-mockito-by-using-junit-rule