Mockito.spy()

It is similar to mock() but instead of return default value it will call the actual implementation when not mocked.

// with annotation
@Spy
private ClassName spy;

// Or with static method
final ClassName spy = Mockito.spy(ClassName.class);

// mock methods that returns something
Mockito.doReturn(value).when(spy).method();

// mock method to throw exception
Mockito.doThrow(new ExceptionClass()).when(spy).metohd();

// mock void methods
Mockito.doNothing().when(spy).method();

Last updated