Sobes.tech
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:

  1. Create a mock using Mockito.mock(Class.class) or the @Mock annotation.
  2. Configure the mock's behavior using when(...).thenReturn(...).
  3. Use the mock in the class being tested.
  4. 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.