0 day streak
java / beginner
Snippet

Mocking Service Dependencies in Controller Tests with MockBean

In Spring Boot testing, @MockBean creates a Mockito mock for a bean and registers it in the Spring ApplicationContext. This replaces actual external services (such as payment providers or third-party APIs) with predictable simulated behavior during test execution.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
@SpringBootTest
public class OrderServiceTest {
@MockBean
private PaymentGateway paymentGateway;
@Test
void testSuccessfulPayment() {
when(paymentGateway.processPayment(100.0)).thenReturn(true);
boolean result = paymentGateway.processPayment(100.0);
assertEquals(true, result);
}
}
spring
Breakdown
1
@MockBean
Registers a Mockito mock instance into the Spring ApplicationContext to replace the real bean.
2
when(paymentGateway.processPayment(100.0)).thenReturn(true);
Configures the mock object to return true whenever processPayment is invoked with 100.0.
3
assertEquals(true, result);
Asserts that the actual returned result matches the expected test value.