mockito Mock Simple Mock


Example

Mockito offers a one-size-fits-all mehtod to create mocks of (non-final) classes and interfaces.

Dependency mock = Mockito.mock(Dependency.class);

This creates a mock instance of Dependency regardless of whether Dependency is a interface or class.

It is then possible to stub method calls to that mock using the Mockito.when(x).thenReturn(y) notation.

Mockito.when(mock.possiblyBuggyMethod()).thenReturn("someString");

So that calls to Dependency.possiblyBuggyMethod() simply return "someString".

There is another notation that is discouraged in most use cases as it is not typesafe.

Mockito.doReturn("someString").when(mock).possiblyBuggyMethod()