java 使用 JUnit @Rule 使用 Mockito 进行参数化测试?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40793464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parameterized testing with Mockito by using JUnit @Rule?
提问by mike rodent
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.
问题是我对 JUnitRule
或这里发生的事情等的了解不够,Runners
无法以 Jeff Bowman 提到的方式解决问题。
回答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.
在您后来的评论中,我发现了差距:您需要将 Mockito 用作规则并将参数化为 Runner,而不是相反。
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.
原因是 Runner 负责报告测试的数量,而 Parameterized 根据测试方法的数量和参数化输入的数量来操纵测试的数量,因此 Parameterized 成为 Runner 流程的一部分非常重要. 相比之下,Mockito runner 或规则的使用只是封装初始化 Mockito 注释和验证 Mockito 使用的方法@Before
和@After
方法,这可以很容易地完成,因为它可以@Rule
与其他@Rule
实例相邻工作——以至于 MockitoJUnitRunner 是非常接近弃用。
To crib directly from the JUnit4 Parameterized Testdoc page and MockitoRuledoc page:
直接从JUnit4 Parameterized Testdoc page 和MockitoRuledoc 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));
}
}