Is it possible to do strict mocks with Mockito?

后端 未结 6 1383
傲寒
傲寒 2021-02-12 20:13

I\'d like to use strict mocks, at least when developing for the first time some tests against old code, so any methods invoked on my mock will throw an exception if I didn\'t sp

6条回答
  •  再見小時候
    2021-02-12 20:51

    You could use verifyNoMoreInteractions. It's useful if the tested class catches exceptions.

    @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();
    }
    

    Result:

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

提交回复
热议问题