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.
// 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);
}
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.
// 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());
}