有没有可能用Mockito做严格的模拟?

2022-09-02 03:31:39

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

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

有可能做到这一点吗?如果是,如何?


答案 1

您希望它做什么?

您可以将其设置为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();
    }
}

答案 2

您可以使用 .如果测试的类捕获异常,这将非常有用。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();
}

结果:

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)
    ...

推荐