← Back to Home

Module 2: Mocking 2

Module Overview

Explore advanced mocking techniques and best practices to improve your testing workflow and increase code reliability.

Advanced Mocking Techniques

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);
}

Learning Objectives

Advanced Verification Techniques

Beyond basic verification, Mockito offers several modes to verify complex interactions:

  • Verifying call counts: Ensure methods are called exactly the expected number of times
  • Capturing arguments: Examine the actual values passed to mocked methods
  • Verifying order: Confirm that method calls happen in the expected sequence
// 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());

Resources