mockito Mock Mock with defaults


Example

While a simple mock returns null (or defaults for primitives) to every call, it is possible to change that behaviour.

Dependency mock = Mockito.mock(Dependency.class, new Answer() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            return "someString";
        }
    });

or using lambdas:

Dependency mock = Mockito.mock(Dependency.class, (Answer) invocationOnMock -> "someString");

This examples return "someString" to every invocation but it is possible to define any logic in the answer-method.