Chapter 3: Mocking with Mockito
Introduction
How to test a UserService that depends on a UserRepository? Without the database, the test fails. The solution: Mock the repository to simulate its behavior.
🎯 Chapter Objectives
By the end of this chapter, you will know how to:
- ✅ Understand why and when to mock
- ✅ Create mocks with @Mock and @InjectMocks
- ✅ Configure behavior with when().thenReturn()
- ✅ Verify calls with verify()
- ✅ Use argument matchers
1. Why Mock?
The Problem
// This class depends on UserRepository
@Service
public class UserService {
private final UserRepository userRepository;
public User findById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
}
}
// How to test without a database?
@Test
void shouldFindUserById() {
UserService service = new UserService(???); // A repository is needed!
}
The Solution: Mocking
@Test
void shouldFindUserById() {
// Create a FAKE repository
UserRepository mockRepo = mock(UserRepository.class);
// Tell it what to return
when(mockRepo.findById(1L)).thenReturn(Optional.of(new User("John")));
// Test the service
UserService service = new UserService(mockRepo);
User user = service.findById(1L);
assertEquals("John", user.getName());
}
2. Basic Setup
With Annotations (Recommended)
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class) // ← Activates Mockito
class UserServiceTest {
@Mock // ← Creates a mock
private UserRepository userRepository;
@InjectMocks // ← Injects the mocks
private UserService userService;
@Test
void shouldFindUserById() {
// when/then here
}
}
Injection Flow
@Mock userRepository ─────┐
├──→ @InjectMocks userService
@Mock anotherDep ─────────┘
3. when().thenReturn()
Return a Value
@Test
void shouldReturnUser() {
// Configure the mock
User mockUser = new User(1L, "John", "john@email.com");
when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser));
// Test
User result = userService.findById(1L);
// Verify
assertEquals("John", result.getName());
}
Return Different Values
@Test
void shouldReturnDifferentUsers() {
when(userRepository.findById(1L)).thenReturn(Optional.of(new User("John")));
when(userRepository.findById(2L)).thenReturn(Optional.of(new User("Jane")));
when(userRepository.findById(99L)).thenReturn(Optional.empty());
assertEquals("John", userService.findById(1L).getName());
assertEquals("Jane", userService.findById(2L).getName());
assertThrows(UserNotFoundException.class, () -> userService.findById(99L));
}
Consecutive Calls
@Test
void shouldReturnDifferentValuesOnConsecutiveCalls() {
when(userRepository.count())
.thenReturn(0L)
.thenReturn(1L)
.thenReturn(2L);
assertEquals(0L, userRepository.count()); // 1st call
assertEquals(1L, userRepository.count()); // 2nd call
assertEquals(2L, userRepository.count()); // 3rd call
assertEquals(2L, userRepository.count()); // Further: last value
}
4. thenThrow() - Simulate Exceptions
@Test
void shouldThrowException() {
when(userRepository.findById(anyLong()))
.thenThrow(new DatabaseException("Connection failed"));
assertThrows(DatabaseException.class, () -> userService.findById(1L));
}
@Test
void shouldThrowThenSucceed() {
when(userRepository.save(any()))
.thenThrow(new RuntimeException("First call fails"))
.thenReturn(new User("Saved"));
// 1st call: exception
assertThrows(RuntimeException.class, () -> userService.save(new User()));
// 2nd call: success
User saved = userService.save(new User());
assertNotNull(saved);
}
5. Argument Matchers
any(), anyLong(), anyString()
@Test
void shouldAcceptAnyId() {
when(userRepository.findById(anyLong())) // Any Long
.thenReturn(Optional.of(new User("Generic")));
assertEquals("Generic", userService.findById(1L).getName());
assertEquals("Generic", userService.findById(999L).getName());
}
Available Matchers
any() // Any object
any(User.class) // Any User
anyLong() // Any long
anyInt() // Any int
anyString() // Any String
anyList() // Any List
anyMap() // Any Map
eq(value) // Exact equality (with other matchers)
isNull() // Null
isNotNull() // Not null
Important Rule: All or Nothing
// ❌ ERROR: Mixing matcher and exact value
when(service.process(anyString(), "fixed")) // ERROR!
// ✅ OK: Use eq() for the exact value
when(service.process(anyString(), eq("fixed")))
argThat() - Custom Matcher
@Test
void shouldMatchCustomCondition() {
when(userRepository.save(argThat(user ->
user.getName() != null && user.getName().length() > 3
))).thenReturn(new User("Saved"));
// Works
User saved = userService.save(new User("John"));
assertNotNull(saved);
// Does not match -> returns null (default mock behavior)
User notSaved = userService.save(new User("Jo"));
assertNull(notSaved);
}
6. verify() - Verify Calls
Simple Verification
@Test
void shouldCallRepository() {
userService.delete(1L);
// Verify that deleteById was called with 1L
verify(userRepository).deleteById(1L);
}
Number of Calls
@Test
void shouldCallRepositoryCorrectTimes() {
userService.processAll();
verify(userRepository, times(3)).save(any()); // Exactly 3 times
verify(userRepository, atLeast(2)).findById(any()); // At least 2 times
verify(userRepository, atMost(5)).count(); // At most 5 times
verify(userRepository, never()).delete(any()); // Never called
}
Order of Calls
@Test
void shouldCallInOrder() {
userService.createAndNotify(new User("John"));
InOrder inOrder = inOrder(userRepository, emailService);
// Verify order
inOrder.verify(userRepository).save(any()); // First save
inOrder.verify(emailService).sendWelcome(any()); // Then email
}
verifyNoMoreInteractions
@Test
void shouldOnlyCallSpecificMethods() {
userService.findById(1L);
verify(userRepository).findById(1L);
verifyNoMoreInteractions(userRepository); // No other calls
}
7. @Spy - Partial Mock
Difference Mock vs Spy
// Mock: All calls are simulated (return null/0/false by default)
@Mock
private UserService mockService;
// Spy: Real implementation, but can override certain methods
@Spy
private UserService spyService;
Usage
@ExtendWith(MockitoExtension.class)
class PartialMockTest {
@Spy
private ArrayList<String> spyList = new ArrayList<>();
@Test
void testSpy() {
// Real call
spyList.add("one");
spyList.add("two");
assertEquals(2, spyList.size());
// Override behavior
when(spyList.size()).thenReturn(100);
assertEquals(100, spyList.size());
// The element is really there
assertEquals("one", spyList.get(0));
}
}
doReturn() vs when() with Spy
@Spy
private UserService userService;
@Test
void testSpy() {
// ❌ PROBLEM: when() calls the real method first!
when(userService.riskyMethod()).thenReturn("safe");
// ✅ SOLUTION: doReturn() does not call the real method
doReturn("safe").when(userService).riskyMethod();
}
8. Capturing Arguments
ArgumentCaptor
@Test
void shouldCaptureArgument() {
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
userService.register("John", "john@email.com", "password");
verify(userRepository).save(userCaptor.capture());
User savedUser = userCaptor.getValue();
assertEquals("John", savedUser.getName());
assertEquals("john@email.com", savedUser.getEmail());
assertNotNull(savedUser.getPassword()); // Encoded
}
With Annotation
@Captor
private ArgumentCaptor<User> userCaptor;
@Test
void shouldCaptureMultipleArgs() {
userService.saveAll(List.of(new User("A"), new User("B")));
verify(userRepository, times(2)).save(userCaptor.capture());
List<User> capturedUsers = userCaptor.getAllValues();
assertEquals(2, capturedUsers.size());
assertEquals("A", capturedUsers.get(0).getName());
assertEquals("B", capturedUsers.get(1).getName());
}
9. Complete Example
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock
private OrderRepository orderRepository;
@Mock
private ProductService productService;
@Mock
private EmailService emailService;
@InjectMocks
private OrderService orderService;
@Captor
private ArgumentCaptor<Order> orderCaptor;
@Test
void shouldCreateOrderSuccessfully() {
// Arrange
Product product = new Product(1L, "Laptop", 1000.0);
when(productService.findById(1L)).thenReturn(Optional.of(product));
when(orderRepository.save(any())).thenAnswer(inv -> {
Order order = inv.getArgument(0);
order.setId(100L);
return order;
});
// Act
Order order = orderService.createOrder(1L, 2, "john@email.com");
// Assert
assertNotNull(order);
assertEquals(100L, order.getId());
assertEquals(2000.0, order.getTotal());
// Verify
verify(productService).findById(1L);
verify(orderRepository).save(orderCaptor.capture());
verify(emailService).sendOrderConfirmation(eq("john@email.com"), any());
Order savedOrder = orderCaptor.getValue();
assertEquals(2, savedOrder.getQuantity());
}
@Test
void shouldThrowWhenProductNotFound() {
// Arrange
when(productService.findById(anyLong())).thenReturn(Optional.empty());
// Act & Assert
assertThrows(ProductNotFoundException.class,
() -> orderService.createOrder(999L, 1, "test@email.com"));
// Verify no order was saved
verify(orderRepository, never()).save(any());
verify(emailService, never()).sendOrderConfirmation(anyString(), any());
}
}
10. Summary
Annotations
| Annotation | Description |
|---|---|
@Mock | Creates a mock |
@InjectMocks | Injects mocks into the tested class |
@Spy | Partial mock (real implementation) |
@Captor | Captures arguments |
@ExtendWith(MockitoExtension.class) | Activates Mockito |
Key Methods
// Configuration
when(mock.method()).thenReturn(value);
when(mock.method()).thenThrow(exception);
doReturn(value).when(spy).method();
// Verification
verify(mock).method();
verify(mock, times(3)).method();
verify(mock, never()).method();
verifyNoMoreInteractions(mock);
// Matchers
any(), anyLong(), anyString()
eq(value)
argThat(condition)
🎯 Next Step
Mockito is perfect for unit tests, but sometimes you need to test with real resources. That's the role of integration tests.
➡️ Chapter 4: Integration Tests