Junior — Middle
What features and methods do you use when writing tests with Mockito?
sobes.tech AI
Answer from AI
When writing tests with Mockito, I use the following features and methods:
- mock() — creating mock objects for interfaces and classes.
- when(...).thenReturn(...) — configuring mock behavior when methods are called.
- verify() — checking that certain methods were called with the correct parameters.
- doThrow(), doAnswer() — for configuring exceptions or complex behavior when calling void methods.
- ArgumentCaptor — capturing arguments passed to mocks for later verification.
- spy() — creating partial mocks that allow calling real methods except those that are mocked.
Example:
List<String> mockedList = Mockito.mock(List.class);
Mockito.when(mockedList.get(0)).thenReturn("first");
String element = mockedList.get(0); // will return "first"
Mockito.verify(mockedList).get(0); // verify method call
These methods help isolate the code under test from external dependencies and verify its behavior.