是否有可能与Mockito做严格的嘲笑?

我想使用严格的模拟,至少在第一次开发针对旧代码的一些测试时,因此如果我没有专门定义期望,那么在我的模拟上调用的任何方法都会抛出exception。

从我所看到的情况来看,如果我没有定义任何期望,Mockito将只返回null,稍后会在其他地方导致NullPointerException。

有可能吗? 如果有,怎么样?

你想要它做什么?

您可以将其设置为RETURN_SMART_NULLS ,这可以避免NPE并包含一些有用的信息。

您可以将其替换为自定义实现,例如,从其answer方法抛出exception:

 @Test public void test() { Object mock = Mockito.mock(Object.class, new NullPointerExceptionAnswer()); String s = mock.toString(); // Breaks here, as intended. assertEquals("", s); } class NullPointerExceptionAnswer implements Answer { @Override public T answer(InvocationOnMock invocation) throws Throwable { throw new NullPointerException(); } } 

您可以使用verifyNoMoreInteractions 。 如果测试类捕获exception,那么它很有用。

 @Test public void testVerifyNoMoreInteractions() throws Exception { final MyInterface mock = Mockito.mock(MyInterface.class); new MyObject().doSomething(mock); verifyNoMoreInteractions(mock); // throws exception } private static class MyObject { public void doSomething(final MyInterface myInterface) { try { myInterface.doSomethingElse(); } catch (Exception e) { // ignored } } } private static interface MyInterface { void doSomethingElse(); } 

结果:

 org.mockito.exceptions.verification.NoInteractionsWanted: No interactions wanted here: -> at hu.palacsint.CatchTest.testVerifyNoMoreInteractions(CatchTest.java:18) But found this interaction: -> at hu.palacsint.CatchTest$MyObject.doSomething(CatchTest.java:24) Actually, above is the only interaction with this mock. at hu.palacsint.stackoverflow.y2013.q8003278.CatchTest.testVerifyNoMoreInteractions(CatchTest.java:18) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) ... 

将此@Rule作为公共字段添加到测试类:

 @RunWith(JUnitParamsRunner.class) public class MyClassTests { @Rule public MockitoRule mockito = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); @Test .... } 

此值已添加到版本2.3.0中的 Mockito

从文档:

确保清洁测试,减少测试代码重复,提高可调试性。 提供灵活性和生产力的最佳组合。 强烈推荐。 计划为Mockito v3的默认设置。 添加以下行为:

  • 提高生产力:当测试中的代码调用带有不同参数的存根方法时,测试会提前失败(请参阅PotentialStubbingProblem)。
  • 清除测试没有不必要的存根:当存在未使用的存根时测试失败(请参阅UnnecessaryStubbingException)。
  • 更清洁,更多DRY测试(“不要重复自己”):如果您使用Mockito.verifyNoMoreInteractions(Object …),则不再需要显式validation存根调用。 它们会自动为您validation。

根据org.mockito.Mockito.RETURNS_DEFAULTS的源代码,它从全局设置中选择“如果没有期望该怎么做”。 此外“如果没有全局配置,那么它使用{@link ReturnsEmptyValues}(返回零,空集合,空值等)”我还没有能够进行该配置。