Junior — Middle
Explain the concept of a Mock object and its use in software testing.
sobes.tech AI
Answer from AI
Mock object is a simulation of a real object or component in testing, which allows isolating the tested code from external dependencies.
Using mock objects helps:
- Test code behavior without the need to access real resources (e.g., database, network).
- Control return values and verify method calls.
- Speed up test execution and increase their reliability.
In Java, libraries like Mockito are often used to create mock objects:
import static org.mockito.Mockito.*;
List mockedList = mock(List.class);
when(mockedList.get(0)).thenReturn("First element");
System.out.println(mockedList.get(0)); // Outputs: First element
verify(mockedList).get(0);
Thus, mock allows testing logic without dependence on real implementations.