Parameterized testing with Mockito by using JUnit @Rule?

*爱你&永不变心* 提交于 2019-12-01 03:21:35
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));
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!