Database and HTTP contract tests
What you will learn
A contract test checks externally observable behavior: request structure, status, payload, or persistent state. A mock HTTP server can test how a client reacts to a response; an actual server test verifies its own transport and routing. A database test must use the database whose semantics are claimed.
- Verify a real loopback HTTP response against an expected contract.
- Test repeated delivery and failure recovery without double effects.
- Explain database migration and rollback evidence.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Framework examples require the companion Maven project or are reviewed artifacts. Their predicted results are not execution evidence.
Actual loopback HTTP contract
public class Main {
public static void main(String[] args) throws Exception {var server=com.sun.net.httpserver.HttpServer.create(new java.net.InetSocketAddress("127.0.0.1",0),0); server.createContext("/items/pen", e -> { try(e) { boolean allowed="alpha".equals(e.getRequestHeaders().getFirst("X-Lab-Tenant")); byte[] body=(allowed?"4":"missing").getBytes(java.nio.charset.StandardCharsets.UTF_8); e.getResponseHeaders().set("Content-Type","text/plain; charset=utf-8"); e.sendResponseHeaders(allowed?200:404,body.length); e.getResponseBody().write(body); } }); server.start(); try(var client=java.net.http.HttpClient.newBuilder().connectTimeout(java.time.Duration.ofSeconds(2)).build()) { for(String tenant:java.util.List.of("alpha","beta")) { var req=java.net.http.HttpRequest.newBuilder(java.net.URI.create("http://127.0.0.1:"+server.getAddress().getPort()+"/items/pen")) .timeout(java.time.Duration.ofSeconds(3)).header("X-Lab-Tenant",tenant).build(); var res=client.send(req,java.net.http.HttpResponse.BodyHandlers.ofString()); System.out.println(res.statusCode()+":"+res.body()); } } finally {server.stop(0);} }}Expected output:
200:4404:missingA test-owned JDK server replies on an ephemeral port; the client reads actual bytes. This is not a Spring or WireMock execution.
HTTP contract boundaries
Specify method, path, required headers, media type, response status and schema. WireMock can start on a dynamic port, stub precise request matches and verify request counts; reset stubs and requests between cases. A stub can model a 503 or malformed response, but cannot prove the remote provider implements that contract. Consumer-driven contracts additionally require provider-side verification. Use fixed local addresses and deadlines; never contact arbitrary external services from tests.
Database and messaging contracts
Apply real migrations to a fresh database and test upgrade from a prior schema too. Assert persisted values after commit and after rollback using a separate transaction when appropriate. Verify duplicate events by checking durable effects, not just how many times a handler was called. Test a failure before acknowledgment and replay with the same ID. A map is useful for modeling idempotency but cannot prove crash atomicity.
Detect duplicate delivery
public class Main {
public static void main(String[] args) {var seen=new java.util.HashSet<String>(); int balance=0; for(String id:java.util.List.of("event-1","event-1","event-2")) if(seen.add(id)) balance+=10; System.out.println(balance); System.out.println(seen.size()); }}Expected output:
202Only the first occurrence changes state. In a durable consumer, recording the ID and updating state must be atomic.
Actual embedded-server test
Source-reviewed, NOT RUN. File lab-fixtures/enterprise-testing-v46/src/test/java/lab/CatalogLiveTest.java; use the companion lab README.
package lab;import java.net.URI;import java.net.http.*;import java.time.Duration;import org.junit.jupiter.api.Test;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.boot.test.web.server.LocalServerPort;import static org.junit.jupiter.api.Assertions.*;@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)class CatalogLiveTest { @LocalServerPort int port; @Test void actualHttpContract() throws Exception { try (var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build()) { var request = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + "/items/pen")) .timeout(Duration.ofSeconds(3)).header("X-Lab-Tenant", "beta").build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); assertEquals(404, response.statusCode()); } }}Predicted behavior: Beta receives 404 on a real socket.
The server is Spring Boot with a random port and explicit client deadline.
Document a provider contract
Source-reviewed, NOT RUN. File lab-fixtures/enterprise-testing-v46/src/test/resources/contracts/catalog.json; use the companion lab README.
{ "method": "GET", "path": "/items/pen", "header": "X-Lab-Tenant", "examples": [ { "tenant": "alpha", "status": 200, "body": { "sku": "pen", "quantity": 4 } }, { "tenant": "beta", "status": 404 } ]}Predicted behavior: Two examples describe expected outcomes.
This is a data contract artifact; it is not an executable contract test.
Common mistakes
Do not assert only a 200 status or compare entire unstable JSON strings. Verify meaningful fields and negative cases. Do not assert rollback based on a mock method call alone.
Practice
Model a transient failure that occurs before an event is recorded; retry with the same event ID and assert exactly one successful effect.
Expected output:
1Compare with the manual review criteria.
Official reading: WireMock · Boot testing · Testcontainers. External test execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Database and HTTP contract tests — knowledge check
Enterprise testing reasoning.
What does a WireMock stub prove?
Which assertion checks a rollback?
What is the purpose of a dynamic port?
What should happen to duplicate delivery?
How verify a consumer-driven contract?