Explore advanced mocking techniques and best practices to improve your testing workflow and increase code reliability.
Once you understand the basics of mocking, you can leverage more sophisticated techniques to handle complex testing scenarios. Mockito provides powerful capabilities for defining precise behavior, verifying interactions, and capturing arguments.
This module builds on the foundation of basic mocking to help you create comprehensive test suites for real-world applications.
// Example of verifying method calls
@Test
public void registerRenter_eligibleDriver_successfullyRegisters() throws NotEligibleToRegisterException {
// GIVEN
String driverLicenseId = "1234ABC567";
Driver driver = new Driver("Danica Patrick", 38, driverLicenseId);
when(driverLicenseService.isValid(driverLicenseId)).thenReturn(true);
// WHEN
renterRegistrar.registerRenter(driver);
// THEN
verify(renterDao).addRenter(driver);
}
Beyond basic verification, Mockito offers several modes to verify complex interactions:
// Verifying number of calls
verify(renterDao, times(1)).addRenter(driver);
// Verification modes
verify(renterDao, atLeastOnce()).addRenter(driver);
verify(renterDao, atMost(3)).getRegisteredRenter(anyString());
verify(renterDao, never()).removeRenter(anyString());
// Using ArgumentCaptor
ArgumentCaptor<Driver> driverCaptor = ArgumentCaptor.forClass(Driver.class);
verify(renterDao).addRenter(driverCaptor.capture());
Driver capturedDriver = driverCaptor.getValue();
assertEquals("Danica Patrick", capturedDriver.getName());