Mocking Multiple Services & Stateful Scenarios
Learn how to mock multiple microservices in a single integration test and handle stateful scenarios like pagination using StableMock.
Real-world microservices rarely talk to just one API. A typical "Checkout" flow might call:
- User Service to get profile data.
- Inventory Service to check stock.
- Payment Gateway to charge the card.
StableMock makes orchestrating these complex, multi-dependency tests trivial.
Mocking Multiple Services
You don't need multiple @WireMockTest annotations or complex port management.
Just list the target APIs in the urls array.
Example: Orchestration Test
This test verifies a flow that aggregates data from two distinct upstream services.
@U(
urls = {
"https://jsonplaceholder.typicode.com", // Service A (User Info)
"https://postman-echo.com" // Service B (Audit Log)
},
properties = {
"app.users.url",
"app.audit.url"
}
)
@SpringBootTest
class OrchestrationTest extends BaseStableMockTest {
@Test
void testAggregatorFlow() {
// 1. Application calls Service A
userService.getUser(1);
// 2. Application calls Service B
auditService.logAccess(1);
// StableMock routes each request to the correct recording folder
// based on the destination URL invoked by your code.
}
} 💡 Code Example: View MultipleAnnotationTest.java to see the full implementation.
Testing Pagination (Scenario Mode)
By default, WireMock is strictly stateless: "If I see Request X, return Response Y".
But what if you need to test a loop that fetches Page 1, then Page 2, then Page 3?
The URL might be the same (/api/items) but the data changes.
Enable scenario = true to activate stateful recording.
@U(
urls = { "https://api.example.com" },
scenario = true // <-- Enables stateful sequencing
)
@SpringBootTest
class PaginationTest extends BaseStableMockTest {
@Test
void testFetchAllPages() {
// First call returns Page 1
client.getPosts();
// Second call returns Page 2
client.getPosts();
// In RECORD mode: stableMock captures the order.
// In PLAYBACK mode: stableMock replays them in the exact same order.
}
} 💡 Code Example: Check out PaginationTest.java for a working example.
Next: Debugging Mocks when things go wrong.