Junior — Middle
Explain the concept of Mockito and how it is used in Java application testing.
sobes.tech AI
Answer from AI
Mockito is a popular library for creating mock objects in Java application tests. Mock objects simulate the behavior of real dependencies (such as services, repositories), allowing you to isolate the class under test and verify its logic without needing to access real external resources.
Main features of Mockito:
- Creating mock objects using
Mockito.mock(). - Configuring mock method behavior with
when(...).thenReturn(...). - Verifying mock method calls with
verify().
Example usage:
import static org.mockito.Mockito.*;
public class UserServiceTest {
@Test
public void testGetUserName() {
UserRepository mockRepo = mock(UserRepository.class);
when(mockRepo.findUserNameById(1)).thenReturn("Alice");
UserService service = new UserService(mockRepo);
String name = service.getUserName(1);
assertEquals("Alice", name);
verify(mockRepo).findUserNameById(1);
}
}
Thus, Mockito helps write unit tests focusing on the logic of the class under test, rather than on real dependencies.