Learn about mocking fundamentals and how to use them in your tests to create isolated and effective unit tests.
Mocking is essential for writing effective unit tests. It allows you to test classes in isolation by creating dummy implementations of their dependencies. This ensures your tests are deterministic, fast, and focused on the specific code you're testing.
Mock objects let you define the output of method calls from dependencies, giving you precise control over test conditions without relying on external systems or real implementation details.
// Example of creating a mock
@Mock
private RenterDao renterDao;
@Mock
private DriverLicenseService driverLicenseService;
@InjectMocks
private RenterRegistrar renterRegistrar;
@BeforeEach
public void setup() {
initMocks(this);
}
// Defining mock behavior
when(renterDao.getRegisteredRenter(driverLicenseId)).thenReturn(driver);
Mocking provides several key benefits in unit testing:
// Example of mocking exceptional behavior
@Test
public void getRegisteredRenter_unregisteredDriver_throwsNotRegisteredException() throws NotRegisteredException {
// GIVEN
String driverLicenseId = "ABC1234567";
when(renterDao.getRegisteredRenter(driverLicenseId)).thenThrow(NotRegisteredException.class);
// WHEN/THEN
assertThrows(NotRegisteredException.class,
() -> renterRegistrar.getRegisteredRenter(driverLicenseId));
}