Junior — Middle
How is the process of simulating objects using the Mockito library in tests carried out?
sobes.tech AI
Answer from AI
Mockito is a library for creating mock objects in Java tests. It allows replacing real dependencies with fake objects to isolate the code under test.
Main steps:
- Create a mock using
Mockito.mock(Class.class)or the@Mockannotation. - Configure the mock's behavior using
when(...).thenReturn(...). - Use the mock in the class being tested.
- Verify method calls using
verify().
Example:
List<String> mockedList = Mockito.mock(List.class);
Mockito.when(mockedList.get(0)).thenReturn("hello");
String result = mockedList.get(0); // returns "hello"
Mockito.verify(mockedList).get(0); // verify method call
Thus, Mockito helps write unit tests by controlling the behavior of dependencies.