← Back to Home

Code-Alongs

Code-Along 1: Mocking 1

Exercise Overview

In this code-along, you'll gain hands-on experience implementing basic mocking techniques with Mockito. You'll learn how to isolate class functionality by mocking dependencies, allowing you to write more deterministic and focused unit tests.

Key Concepts Covered:

  • Setting up Mockito in a project
  • Creating mock objects using @Mock annotation
  • Injecting mocks into classes under test with @InjectMocks
  • Stubbing method responses with when() and thenReturn()
  • Testing exception handling with thenThrow()
// Example snippet from the code-along
@Test
public void testServiceWithMockedDependency() {
    // GIVEN
    String orderId = "12345";
    Order testOrder = new Order(orderId, "Customer1", 99.99);
    when(orderDao.getOrder(orderId)).thenReturn(testOrder);
    
    // WHEN
    Order result = orderService.lookupOrder(orderId);
    
    // THEN
    assertEquals(orderId, result.getId());
    assertEquals("Customer1", result.getCustomerName());
    assertEquals(99.99, result.getAmount(), 0.001);
}

Code-Along 2: Mocking 2

Exercise Overview

This code-along builds on the foundation established in the first exercise, introducing more advanced mocking techniques for complex testing scenarios. You'll work with a more sophisticated application that requires advanced verification and argument capturing.

Key Concepts Covered:

  • Verifying method calls with verify()
  • Controlling verification specificity with argument matchers
  • Capturing and asserting on method arguments
  • Verifying call counts and interaction order
  • Best practices for test organization and readability
// Example snippet from the code-along
@Test
public void testServiceSavesValidatedData() {
    // GIVEN
    User user = new User("jsmith", "John Smith", "jsmith@example.com");
    when(validator.isValidUser(any(User.class))).thenReturn(true);
    
    // WHEN
    userService.createUser(user);
    
    // THEN
    // Verify the validator was called with the user
    verify(validator).isValidUser(user);
    
    // Capture the argument passed to repository.save()
    ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
    verify(userRepository).save(userCaptor.capture());
    
    // Assert on the captured argument
    User savedUser = userCaptor.getValue();
    assertEquals("jsmith", savedUser.getUsername());
    assertEquals("John Smith", savedUser.getName());
    assertEquals("jsmith@example.com", savedUser.getEmail());
}