How do you mock microservices during testing?

Mocking microservices during testing allows us to verify the behavior of a service without depending on actual external services. Instead of calling real microservices, we simulate their responses using mock servers or mock objects. This makes tests faster, more reliable, and independent of network or service availability.

Key Points

Example

Suppose an Order Service calls a Payment Service to process payments.

In production

Order Service

↓

Payment Service

During testing

Order Service

↓

WireMock Server

↓

Mock Response

The Order Service believes it is communicating with the real Payment Service, while WireMock returns predefined responses.

WireMock Setup

stubFor(post(urlEqualTo("/payments"))
    .willReturn(
        aResponse()

.withStatus(200)

.withBody(

{\"status\":\"SUCCESS\"}

)));

When the application calls

POST /payments

WireMock returns

{

status": "SUCCESS

}

Common Approaches

1. WireMock

2. Mockito

Example

@Mock
private PaymentService paymentService;

when(paymentService.processPayment())

.thenReturn("SUCCESS");

3. Spring Cloud Contract

4. MockWebServer

Testing Levels

Unit Testing

Integration Testing

Contract Testing

Benefits

Real-World Example

An E-Commerce Application

Services

While testing Order Service

This allows testing Order Service independently without running all microservices.

Failure Scenario Testing

Mock a timeout

stubFor(get(urlEqualTo("/payment"))
    .willReturn(
        aResponse()
        .withFixedDelay(10000)));

This helps verify

Best Practice

Interview Tip

A concise interview answer is: To mock microservices during testing, I typically use Mockito for unit testing and WireMock for integration testing. These tools simulate external service behavior by returning predefined responses, allowing tests to run independently of actual microservices. This improves test reliability, speed, and enables testing of both success and failure scenarios without requiring external systems to be available.

Last updated: 11 November 2026

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

Next question: Explain the process of creating a Docker image for a Spring Boot application.

More Spring Boot - Level II interview questions

All Spring Boot - Level II questions