MockitoJUnitRunner 为您提供框架使用的自动验证,以及自动的initMocks()。
框架使用的自动验证确实值得拥有。如果您犯了这些错误之一,它会为您提供更好的报告。
您调用静态 when 方法,但未使用匹配的 thenReturn、thenThrow 或 then 完成存根。 (下面代码中的错误 1)
您在模拟上调用 verify,但忘记提供方法调用
您正在尝试验证。 (下面代码中的错误 2)
在doReturn、doThrow 或之后调用when 方法
doAnswer 并通过一个模拟,但忘记提供方法
你正在尝试存根。 (下面代码中的错误 3)
如果您没有验证框架使用情况,则在以下调用 Mockito 方法之前不会报告这些错误。这可能是
- 在相同的测试方法中(如下面的错误1),
- 在下一个测试方法中(如下面的错误2),
- 在下一个测试班。
如果它们发生在您运行的最后一次测试中(如下面的错误 3),则根本不会报告它们。
以下是每种类型的错误的外观。假设 JUnit 按此处列出的顺序运行这些测试。
@Test
public void test1() {
// ERROR 1
// This compiles and runs, but it's an invalid use of the framework because
// Mockito is still waiting to find out what it should do when myMethod is called.
// But Mockito can't report it yet, because the call to thenReturn might
// be yet to happen.
when(myMock.method1());
doSomeTestingStuff();
// ERROR 1 is reported on the following line, even though it's not the line with
// the error.
verify(myMock).method2();
}
@Test
public void test2() {
doSomeTestingStuff();
// ERROR 2
// This compiles and runs, but it's an invalid use of the framework because
// Mockito doesn't know what method call to verify. But Mockito can't report
// it yet, because the call to the method that's being verified might
// be yet to happen.
verify(myMock);
}
@Test
public void test3() {
// ERROR 2 is reported on the following line, even though it's not even in
// the same test as the error.
doReturn("Hello").when(myMock).method1();
// ERROR 3
// This compiles and runs, but it's an invalid use of the framework because
// Mockito doesn't know what method call is being stubbed. But Mockito can't
// report it yet, because the call to the method that's being stubbed might
// be yet to happen.
doReturn("World").when(myMock);
doSomeTestingStuff();
// ERROR 3 is never reported, because there are no more Mockito calls.
}
现在当我五年多前第一次写这个答案时,我写了
所以我建议尽可能使用MockitoJUnitRunner。但是,正如 Tomasz Nurkiewicz 正确指出的那样,如果您需要另一个 JUnit 运行器,例如 Spring 运行器,则不能使用它。
我的建议现在已更改。自从我第一次写这个答案以来,Mockito 团队添加了一个新功能。这是一个 JUnit 规则,它执行与MockitoJUnitRunner 完全相同的功能。但这样更好,因为它不排除其他跑步者的使用。
包括
@Rule
public MockitoRule rule = MockitoJUnit.rule();
在你的测试课上。这会初始化模拟,并自动执行框架验证;就像MockitoJUnitRunner 一样。但现在,您也可以使用 SpringJUnit4ClassRunner 或任何其他 JUnitRunner。从 Mockito 2.1.0 开始,有更多选项可以准确控制报告的问题类型。