How can you mock external services in a Spring Boot test?

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

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.

@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

Alternative Tool: WireMock

WireMock is commonly used when testing REST API integrations.

Example

External API Call

↓

WireMock Server

↓

Mock Response

Advantages of WireMock

When to Use Each Approach

1. @MockBean + Mockito

2. WireMock

Benefits

Real-World Example

In an e-commerce application

Order Service

↓

Payment Service

↓

Inventory Service

During testing

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.

Last updated: 1 November 2026

Previous question: What is Spring Boot DevTools used for?

Next question: How do you mock microservices during testing?

More Spring Boot - Level II interview questions

All Spring Boot - Level II questions