← Back to Home

Module 1: Mocking 1

Module Overview

Learn about mocking fundamentals and how to use them in your tests to create isolated and effective unit tests.

Introduction to Mocking

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

Learning Objectives

When to Use Mocking

Mocking provides several key benefits in unit testing:

  • Deterministic tests: Tests produce predictable results regardless of external factors
  • Testing edge cases: Easily test rare conditions that are difficult to reproduce naturally
  • Speed: Tests run faster without waiting for real dependencies like databases or networks
  • Cost efficiency: Avoid expenses associated with real services or resources
  • Isolation: Test only your specific code unit without interference from dependencies
// 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));
}

Resources