使用Mockitos传递参数化的输入 [英] passing Parameterized input using Mockitos
问题描述
我正在使用Mockito进行单元测试.我想知道是否有可能像Junit测试中那样发送参数化的输入参数
例如
I am using Mockito for unit testing. I am wondering if its possible to send Parametrized input parameters with as in Junit testing
e.g
@InjectMocks
MockClass mockClass = new MockClass();
@Test
public void mockTestMethod()
{
mockClass.testMethod(stringInput);
// here I want to pass a list of String inputs
// this is possible in Junit through Parameterized.class..
// wondering if its can be done in Mockito
}
推荐答案
在JUnit中,参数化测试使用
In JUnit, Parameterized tests use a special runner that ensure that the test is instantiated multiple times, so each test method is called multiple times. Mockito is a tool for writing specific unit tests, so there is no built-in ability to run the same test multiple times with different Mockito expectations.
如果您希望更改测试条件,最好的选择是执行以下一项操作:
If you want your test conditions to change, your best bet is to do one of the following:
- 使用JUnit参数化您的测试,并为所需的模拟输入提供参数;
- 在测试中运行不同参数的循环,不幸的是避免了每种方法测试一件事"的思想
- 提取一个实际执行测试的方法,并为所需的每个模拟创建一个新的
@Test
方法.
- Parameterize your test using JUnit, with a parameter for the mock inputs you want;
- Run a loop of different parameters in your test, which unfortunately avoids the "test one thing per method" philosophy
- Extract a method that actually performs the test, and create a new
@Test
method for each mock you want.
请注意,没有禁止将模拟对象用作@Parameterized
测试参数.如果您希望基于模拟进行参数化,则可以执行此操作,可能会创建模拟并在测试的静态方法中设置期望值.
Note that there's no prohibition on using mock objects as @Parameterized
test parameters. If you're looking to parameterize based on mocks, you can do that, possibly creating the mock and setting the expectations in a static method on the test.
有关跑步者的注意事项:此 MockitoJUnitRunner :每个测试类只能有一个运行器.您将要切换到 @Before和@After方法或
Note about runners: This Parameterized test runner conflicts with Mockito's MockitoJUnitRunner: Each test class can only have one runner. You'll want to switch to @Before and @After methods or a Mockito JUnit4 rule for your setup, if you use them both.
例如,从一个不同的答案压缩而来,详细说明了参数化运行程序与JUnit规则以及如何从 JUnit4参数化测试文档页面和
As an example, compressed from a different answer that explains more about Parameterized runners versus JUnit rules and lifting 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 the values */ }
public YourComponentTest(Parameter parameter) { /* Save the parameter to a field */ }
@Test public void test() { /* Use the field value in assertions */ }
}
这篇关于使用Mockitos传递参数化的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!