Performance: @MockBean for mocking dependencies
This affects test execution speed and memory usage during Spring Boot integration tests.
@MockBean
private RealService realService;
@Test
void testService() {
when(realService.callExternalApi()).thenReturn(mockResponse);
// test assertions
}@Autowired
private RealService realService;
@Test
void testService() {
// realService calls external resources
realService.callExternalApi();
// test assertions
}| Pattern | Bean Initialization | External Calls | Test Runtime | Verdict |
|---|---|---|---|---|
| Using real beans | Full initialization | Yes, real external calls | Slower due to blocking | [X] Bad |
| Using @MockBean | Mock initialization only | No external calls | Faster and lightweight | [OK] Good |
@MockBean in a Spring Boot test?UserService in a Spring Boot test?@MockBean
private PaymentService paymentService;
@Test
void testProcess() {
when(paymentService.pay()).thenReturn(true);
boolean result = paymentService.pay();
System.out.println(result);
}@MockBean
private OrderService orderService;
@Test
void testOrder() {
orderService.placeOrder();
verify(orderService).placeOrder();
}NotificationService that depends on EmailSender. You want to test NotificationService without sending real emails. Which setup correctly uses @MockBean to mock EmailSender and verify sendEmail() was called once during the test?Pass the test and this pattern moves unknown