Mock REST API Spring Boot Testing: The Definitive Guide
Learn the best strategies to mock REST APIs in Spring Boot testing. Compare @MockBean, WireMock, and StableMock for reliable microservice integration tests.
The Three Levels of REST API Mocking
When testing a Spring Boot application that calls other REST APIs, you have three main strategies. Choosing the wrong one can lead to flaky tests or low confidence.
Level 1: @MockBean (The Unit Test Approach)
The fastest way to test is to mock the component that makes the call (e.g., your `UserService` or `RestTemplate`).
@MockBean
private RestTemplate restTemplate;
@Test
void testGetUser()
when(restTemplate.getForObject("/users/1", User.class))
.thenReturn(new User("John"));
// ... assertions
Pros: Extremely fast. No network overhead.
Cons: Dangerous. You aren't testing serialization, URL construction, or HTTP error handling.
If the real API returns `{"full_name": "John"}` instead of `{"name": "John"}`, your test passes but prod fails.
Level 2: WireMock (The Manual Integration)
WireMock spins up a real HTTP server. Your code makes actual HTTP calls to `localhost`.
stubFor(get(urlEqualTo("/users/1"))
.willReturn(aResponse()
.withHeader("Content-Type", "application/json")
.withBody("{\"name\": \"John\"}"))); Pros: Realistic. Tests HTTP layer, headers, and serialization.
Cons: Maintenance heavy. You essentially have to rewrite the API behavior in JSON.
If the API changes, you must manually update the test.
Level 3: StableMock (The Smart Integration)
StableMock gives you the realism of WireMock with the speed of `@MockBean`.
- Record: Run against the real DEV API once. StableMock saves the response.
- Replay: Future runs use the saved response (Stub).
- Verify: StableMock ensures your code sends the exact same request body/headers as it did during recording.
@SpringBootTest
@U(urls = "https://api.example.com", properties = "app.api.url")
class MyApiTest extends BaseStableMockTest
@DynamicPropertySource
static void configure(DynamicPropertyRegistry registry)
autoRegisterProperties(registry, MyApiTest.class);
@Test
void testRealApiIntegration()
// Just call your service. StableMock handles the rest.
userService.fetchUser(1);
Which One Should You Choose?
| Goal | Recommended Tool |
|---|---|
| Unit testing complex business logic | @MockBean |
| Testing edge cases (timeouts, 500 errors) | WireMock |
| End-to-End integration testing | StableMock |
Upgrade Your Test Suite
Stop manually writing JSON strings. Start recording real interactions.
Read next: Mocking Feign Clients in Spring Boot or Full Spring Boot Integration Testing Guide.