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

dev*_*ium 16 java testing unit-testing mocking mockito

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

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

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

Dav*_*ton 15

你想要它做什么?

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

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

@Test
public void test() {
    Object mock = Mockito.mock(Object.class, new NullPointerExceptionAnswer());
    String s = mock.toString(); // Breaks here, as intended.
    assertEquals("", s);
}

class NullPointerExceptionAnswer<T> implements Answer<T> {
    @Override
    public T answer(InvocationOnMock invocation) throws Throwable {
        throw new NullPointerException();
    }
}
Run Code Online (Sandbox Code Playgroud)


pal*_*int 8

你可以用verifyNoMoreInteractions.如果测试类捕获异常,它会很有用.

@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();
}
Run Code Online (Sandbox Code Playgroud)

结果:

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)
    ...
Run Code Online (Sandbox Code Playgroud)


Mat*_*ein 6

将其@Rule作为公共字段添加到您的测试班级:

@RunWith(JUnitParamsRunner.class)
public class MyClassTests {

    @Rule
    public MockitoRule mockito = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);

    @Test
    ....
}
Run Code Online (Sandbox Code Playgroud)

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

从文档中:

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

  • 更高的生产率:当被测代码调用带有不同参数的存根方法时,测试会尽早失败(请参阅PotentialStubbingProblem)。
  • 干净的测试,没有不必要的存根:存在未使用的存根时,测试将失败(请参阅UnnecessaryStubbingException)。
  • 更干净,更干燥的测试(“不要重复自己”):如果使用Mockito.verifyNoMoreInteractions(Object ...),则不再需要显式验证存根调用。它们会自动为您验证。