Prompt
How do I mock an internal service for contract testing?
Latest observation
To mock an internal service for contract testing, the goal is usually not to create a generic fake, but to provide a predictable implementation that obeys the agreed API contract so your consumer tests can run without the real service.
Typical approaches
1) Use a contract-testing tool that generates mocks
If you’re doing consumer-driven contract testing, tools like:
- Pact
- Spring Cloud Contract
- WireMock (often paired with contract definitions)
can generate a mock server from the contract or stubs from recorded interactions.
Best when: you want the mock to be derived from the contract automatically.
2) Build a stub server for the internal service
Create a small HTTP server that returns canned responses for the endpoints your consumer uses.
Example responsibilities:
- Return expected success responses
- Return error cases your consumer needs to handle
- Match on request path, method, headers, and body
- Keep response schemas aligned with the contract
Best when: you need simple, controlled behavior and don’t want full tooling.
3) Mock at the client boundary in your tests
If you only need unit tests, mock the service client interface rather than the service itself.
Example:
- In Java: mock the
InternalServiceClient - In Python: patch the HTTP client call
- In JavaScript: mock the API wrapper module
Best when: you want fast isolated tests, not full contract verification.
Good practice for contract testing
For contract tests, the mock should:
- Mirror the real API shape: endpoints, request/response schema, status codes
- Be strict enough to catch breaking changes
- Only implement interactions actually used by the consumer
- Avoid business logic unless the contract requires it
- Be versioned with the contract
Example with WireMock
You can stub responses like this:
{
"request": {
"method": "GET",
"urlPath": "/users/123"
},
"response": {
"status": 200,
"body": "{\"id\":123,\"name\":\"Alice\"}",
"headers": {
"Content-Type": "application/json"
}
}
}
Then your consumer test hits the mock instead of the real service.
Example with Pact conceptually
- Consumer test defines expected interaction.
- Pact creates a contract file.
- Provider verification checks the real service against the contract.
- Consumer can run against the Pact mock server locally.
Recommendation
If your goal is contract testing, use one of these:
- Pact if you want consumer-driven contracts
- Spring Cloud Contract if you’re in the Spring ecosystem
- WireMock if you want lightweight HTTP stubs
If you want, I can show you:
- a specific example in your language/framework
- how to set up Pact or WireMock
- how to mock an internal gRPC service instead of HTTP