Is it possible to do strict mocks with Mockito?

后端 未结 6 1382
傲寒
傲寒 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条回答
  •  梦毁少年i
    2021-02-12 20:55

    What do you want it to do?

    You can set it to RETURN_SMART_NULLS, which avoids the NPE and includes some useful info.

    You could replace this with a custom implementation, for example, that throws an exception from its answer method:

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

提交回复
热议问题