15

这是从这个问题开始的:我被要求开始一个新问题。

Rule问题是我对 JUnit或这里发生的事情等了解不够Runners,无法以 Jeff Bowman 提到的方式解决问题。

4

1 回答 1

31

在您后来的评论中,我发现了差距:您需要将 Mockito 用作规则并将参数化为 Runner,而不是相反。

原因是Runner负责上报测试数量,而Parameterized根据测试方法的数量和参数化输入的数量来操纵测试的数量,所以Parameterized成为Runner过程的一部分真的很重要. 相比之下,使用 Mockito 运行程序或规则只是封装初始化 Mockito 注释和验证 Mockito 使用的@Before方法@After,这可以很容易地完成,因为@Rule它与其他实例相邻工作@Rule- 以至于 MockitoJUnitRunner 是几乎被弃用了

要直接从JUnit4 Parameterized Test doc page 和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));
    }
}
于 2016-11-24T21:40:46.663 回答