使用JUnit @Rule使用Mockito进行参数化测试? [英] Parameterized testing with Mockito by using JUnit @Rule?

查看:347
本文介绍了使用JUnit @Rule使用Mockito进行参数化测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是这个问题:我被问到的地方开始一个新问题。

This follows on from this question: where I am asked to start a new question.

问题是我对JUnit 规则了解不够,或者这里用 Runners 等来解决问题,以Jeff Bowman提到的方式解决问题。

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.

推荐答案

在你后来的评论中,我找出了差距:你需要使用Mockito作为规则并参数化为跑步者,而不是相反。

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.

原因是Runner负责报告测试次数,Parameterized根据测试方法的数量和参数化输入的数量来操作测试次数,因此对于参数化来说非常重要。成为Runner流程的一部分。相比之下,使用Mockito运行器或规则只是封装 @Before @After 初始化方法Mockito注释和验证Mockito用法,可以非常轻松地完成 @Rule ,与其他 @Rule 相邻实例 - MockitoJUnitRunner 几乎已弃用

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.

直接来自 JUnit4参数化测试 doc页面和 MockitoRule doc page:

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));
    }
}

这篇关于使用JUnit @Rule使用Mockito进行参数化测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆