External services can be mocked in Spring Boot tests to avoid making real network calls during test execution. Mocking allows us to simulate the behavior of third-party APIs, microservices, databases, or external systems, making tests faster, more reliable, and independent of external dependencies.
Key Points: • Mocking external services helps isolate application logic during testing. • @MockBean replaces actual Spring beans with mock implementations in the test context. • Tools such as Mockito and WireMock are commonly used for mocking service behavior.
Example: Suppose an Order Service communicates with a Payment Service. During testing, instead of calling the real Payment Service, we can mock its response and verify how the Order Service behaves.
Code Example:
@SpringBootTest
class OrderServiceTest {
@MockBean
private PaymentService paymentService;
@Autowired
private OrderService orderService;
@Test
void testPlaceOrder() {
Mockito.when(paymentService.processPayment())
.thenReturn("SUCCESS");
String result =
orderService.placeOrder();
assertEquals(
"ORDER_CREATED",
result);
}
}How @MockBean Works:
Application Context ↓ Real PaymentService Bean ↓ Replaced By ↓ Mock PaymentService Bean
When the test runs:
• Spring injects the mock bean. • No real external call is made. • Mock behavior is controlled using Mockito.
Alternative Tool: WireMock
WireMock is commonly used when testing REST API integrations.
Example:
External API Call ↓ WireMock Server ↓ Mock Response
Advantages of WireMock:
• Simulates real HTTP responses. • Supports request validation. • Useful for integration testing.
When to Use Each Approach:
1. @MockBean + Mockito
• Unit Tests • Service Layer Testing • Fast execution
2. WireMock
• Integration Tests • REST Client Testing • Microservice Communication Testing
Benefits:
• Faster test execution. • No dependency on external systems. • Predictable test results. • Easier testing of error scenarios. • Improved test stability.
Real-World Example:
In an e-commerce application:
Order Service ↓ Payment Service ↓ Inventory Service
During testing:
• Payment Service is mocked. • Inventory Service is mocked.
This allows the Order Service to be tested independently without requiring other services to be running.
Interview Tip: A concise interview answer is: In Spring Boot, external services can be mocked using @MockBean, which replaces the actual bean in the Spring context with a Mockito mock. For REST-based integrations, tools like WireMock can simulate real HTTP responses. This approach makes tests faster, reliable, and independent of external service availability.