3 回答

TA贡献1811条经验 获得超4个赞
MockitoJUnitRunner为您提供框架使用情况的自动验证,以及自动验证initMocks()。
框架使用的自动验证实际上是值得的。如果您犯了这些错误之一,它可以为您提供更好的报告。
您调用静态when方法,但不具有匹配完成磕碰thenReturn,thenThrow或then。 (以下代码中的错误1)
您调用verify了一个模拟,但是忘记提供您尝试验证的方法调用。(以下代码中的错误2)
您when在或 之后调用该方法doReturn,并传递一个模拟,但是忘记提供您尝试存根的方法。 (以下代码中的错误3)doThrowdoAnswer
如果您没有验证框架使用情况,则在以下对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开始,还有其他选项可精确控制要报告的问题类型。

TA贡献1840条经验 获得超5个赞
使用runner可以节省一些编码(不需要@Before方法)。另一方面,有时无法使用跑步者,例如,当您已经在使用跑步者时SpringJUnit4ClassRunner。
而已。这只是一个偏好问题。
添加回答
举报