Mockito is a mocking framework that lets you write beatiful tests with clean and simple API. It biases toward minimal specifications, makes different behaviors look different, and displays clear error messages.
Creating Mocks
To create a mock using Mockito, simply annotate mocks with @Mock
and call MockitoAnnotations.initMocks(this)
.
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class FooClassTest {
@Mock
mockFoo;
public void setUp() {
MockitoAnnotations.initMocks(this);
...
}
...
}
Stubbing values
Stubbing values can stimulate the behavior of exsiting code or be a temporary substitute for yet-to-be-developed code. By default, for all methods that return value, mock returns null, an empty collection or appropriate primitive/primitive wrapper value (e.g: 0, false, …). You can override the stubbing values as below. Once stubbed, the method will always return stubbed value regardless of how many times it is called. For a method with a void return, ususally we do not need to stub it.
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
...
// a method that returns values
when(mockFoo.someCall()).thenReturn(someValue);
when(mockFoo.someCall()).thenThrow(new FooException());
// a method with a void return
doThrow(new FooException()).when(mockFoo).voidMethodThatThrows();
read more