mockito3 cheat sheet
by Adrian Więch
CREATE
AR GUMENT CA PTORS
//mocks: default values returned by default
1. Define:
ClassName mock = mock(ClassName.class)
;
@Captor
or use: @Mock
private ArgumentCaptor<Double>
doubleCaptor;
//spies: class logic used by default
ClassName spy = spy(ClassName.class)
;
2. Capture :
or use: @Spy
verify(mock, times(1)).method(eq(val),
doubleCaptor.capture());
//static mocks: use try-with-resources
MockedStatic<ClassName> mock =
3. Get va lue:
mockStatic(
ClassName.class));
double capturedArgument =
doubleCaptor.getValue();
DEFINE BEHAVIOUR
//mocks
MOCKITO BD D
- when(mock.sampleMethod())
.thenReturn(sampleVal);
// when...thenReturn
- when(mock.sampleMethod())
given(mock.method())
.willReturn(val);
.thenThrow(SampleException.class);
- when(mock.sampleMethod())
// veri fy(class, times( 1)).method()
.thenAnswer(inv -> ...)
then(mock).should(times(1)).method();
//spies or void methods
- doReturn(value)
SAMPLE TE ST WITH A MOCK
.when(spy).method();
- doThrow(new ExceptionClass())
.when(spy).metohd();
@ExtendWith(MockitoExtension.class)
- doNothing().when(spy).method();
class ForCheatSheet {
@InjectMocks
//static mocks
private BookingService bookingService;
staticMock.when(() ->
StaticClass.method().thenReturn(val);
@Mock
private RoomService roomServiceMock;
//argument matchers
@Test
when(mock.sampleMethod(any(),
void sample() {
anyDouble())).thenReturn(sampleVal);
// given
when(this.roomServiceMock.getAvailableRooms())
.thenReturn(Collections.singletonList(new
Room("Room 1", 5)));
VERIFY BEHAVIOUR
int expected = 5;
// when
//method() invoked once
int actual =
- verify(mockClass, times(1)).method();
bookingService.getAvailablePlaceCount();
//method never invoked
// then
- verify(mockClass, never()).method();
assertEquals(expected, actual);
//no more methods invoked
- verifyNoMoreInteractions(mockClass);