Software Testing & Quality
Integration Testing with Real Dependencies: Testcontainers, WireMock and Contracts
Intermediate8 min readUpdated
An integration test earns its cost by exercising something a unit test cannot: a real SQL dialect, a real serialiser, a real broker. This framework-neutral guide covers choosing the boundary under test, running dependencies with Testcontainers, keeping state clean between tests, stubbing outbound HTTP with WireMock and pinning APIs with consumer-driven contracts.
What you will learn
- Identify precisely which boundary a test exercises and what its failure would mean
- Run real databases, brokers and dependencies from a test with Testcontainers
- Choose a state-reset strategy that keeps tests isolated without making them slow
- Stub outbound HTTP calls with WireMock including failure and latency scenarios
- Verify API compatibility with consumer-driven contract tests instead of shared end-to-end suites
A unit test proves that your logic is self-consistent. It cannot tell you that the SQL is valid for the engine you deploy on, that the JSON your client sends matches what the provider expects, that the migration runs, that the message you publish can be deserialised by the consumer, or that the transaction boundary you drew actually commits. Those are integration questions, and every one of them has caused a production incident somewhere this week.
Integration tests are also the layer where suites go wrong most expensively: slow, order-dependent, environment-hungry and flaky. The difference between a suite that pays for itself and one that gets deleted after a year comes down to a small number of decisions — what boundary each test covers, where its dependencies come from, and how state is reset. This guide is framework-neutral; for the Spring-specific mechanics see the Spring Boot testing guide and the Spring Framework testing guide.
Name the boundary first
"Integration test" covers tests whose scope ranges from two classes to an entire deployment. Before writing one, answer a single question: if this test goes red, what have I learned? A test whose failure could mean any of eleven things is a smoke alarm without an address.
The boundaries worth testing separately are usually these:
- Persistence. Your repository code against the real database engine, with the real schema produced by the real migrations. Catches invalid SQL, mapping errors, missing indexes on a unique constraint, and migrations that fail on a non-empty table.
- Serialisation. An object graph through the actual serialiser and back. Catches date formats, null handling, unknown-property behaviour and the field someone renamed.
- Outbound HTTP. Your client against a controlled stub. Catches URL construction, headers, authentication, timeout and retry behaviour, and error mapping.
- Messaging. Publish and consume through a real broker. Catches serialisation, headers, partitioning, acknowledgement semantics and redelivery.
- The composed application. The service started as it will be deployed, exercised through its public API. Catches wiring, configuration and cross-cutting concerns.
Each of those has a different subject and a different failure meaning. Bundling them into one "integration test" that starts everything and clicks through a browser gives you the union of their costs and none of their diagnostic value.
Contract or integration?
There is a further split that saves a great deal of pain in a system of several services. Integration testing asks whether two components work together right now, in one process or one environment. Contract testing asks whether the agreement between them still holds, and it does so without both components ever running at the same time.
The distinction matters because integration tests across services do not scale. A shared environment where every team deploys before running end-to-end tests becomes a queue, then a bottleneck, then a source of failures nobody owns. Contract testing replaces most of that with two independently runnable test suites and a file passed between them.
Real dependencies with Testcontainers
Testcontainers starts Docker containers from JUnit and shuts them down afterwards, which removes the last excuse for testing against substitutes.
@Testcontainers
class OrderRepositoryIT {
@Container
static final PostgreSQLContainer<?> POSTGRES =
new PostgreSQLContainer<>("postgres:17-alpine")
.withDatabaseName("shop")
.withReuse(true);
static DataSource dataSource;
@BeforeAll
static void migrate() {
HikariConfig config = new HikariConfig();
config.setJdbcUrl(POSTGRES.getJdbcUrl());
config.setUsername(POSTGRES.getUsername());
config.setPassword(POSTGRES.getPassword());
dataSource = new HikariDataSource(config);
Flyway.configure().dataSource(dataSource).load().migrate();
}
@Test
void findsOrdersPlacedInAWindowInPlacedOrder() {
OrderRepository repository = new JdbcOrderRepository(dataSource);
repository.save(anOrder().placedAt("2026-01-05T10:00:00Z").build());
repository.save(anOrder().placedAt("2026-01-06T10:00:00Z").build());
repository.save(anOrder().placedAt("2026-02-01T10:00:00Z").build());
List<Order> found = repository.placedBetween(
Instant.parse("2026-01-01T00:00:00Z"), Instant.parse("2026-01-31T23:59:59Z"));
assertThat(found).hasSize(2)
.extracting(Order::placedAt)
.isSorted();
}
}
Three details do most of the work. Declaring the container static starts it once for the whole class rather than once per test method. Running the real migrations means the test also proves them. And pinning an exact image tag — postgres:17-alpine, not postgres:latest — keeps the suite reproducible when someone rebuilds the image next month.
For a whole suite, a singleton container started once in a static initialiser and never stopped is faster still; the JVM exits and Testcontainers' reaper removes the container. withReuse(true) combined with the local testcontainers.properties reuse flag keeps a container alive between local runs, cutting the start-up cost during development while CI still starts clean.
Beyond databases there are modules for Kafka, RabbitMQ, Redis, Elasticsearch, LocalStack and a generic container that runs any image with a wait strategy of your choosing:
@Container
static final GenericContainer<?> LEGACY_PRICING =
new GenericContainer<>("registry.example.com/pricing:3.4")
.withExposedPorts(8080)
.withEnv("PRICING_MODE", "test")
.waitingFor(Wait.forHttp("/health").forStatusCode(200));
Wait strategies matter more than they look. A container whose port is open but whose application has not finished booting produces exactly the kind of intermittent failure that erodes trust in a suite.
Keeping tests from poisoning each other
Once tests share a real database, isolation stops being free. Three strategies, with honest trade-offs:
Transactional rollback. Wrap each test in a transaction and roll it back. It is the fastest option and needs no cleanup code, but it hides everything that happens at commit — deferred constraints, commit-time hooks, triggers — and it does not work when the code under test opens its own transaction or the request crosses a process boundary.
Clean state between tests. Truncate the affected tables (or restore a template database) before each test. Slower, but the test sees exactly what production would. A single TRUNCATE ... RESTART IDENTITY CASCADE over the handful of tables involved is usually fast enough.
Unique data per test. Give each test its own tenant, customer or key prefix so collisions are impossible and nothing needs cleaning. This is the only strategy that survives aggressive parallel execution, and it also forces the code to be tenant-safe, which is often a genuine requirement.
Whichever you choose, apply it uniformly. Suites where some classes roll back and others truncate fail in ways that depend on execution order, and diagnosing that costs more than the time either strategy saved.
Test data you can read
Integration tests need more setup data than unit tests, and setup is where they become unreadable. The two patterns that work:
// Builder with meaningful defaults: the test states only what it cares about.
Order order = anOrder()
.forCustomer(aCustomer().premium().build())
.withLine("SKU-1", 2, "24.00")
.placedAt("2026-01-05T10:00:00Z")
.build();
A test data builder supplies valid defaults for every field and lets each test override the two or three that are relevant. When a required column is added, one builder changes rather than sixty tests. An object mother goes further and names whole scenarios — Orders.shippedInternationalOrder() — which suits cases that recur across many tests.
Avoid the alternative that always appears first: a shared SQL fixture file loaded before the suite, containing a hundred rows that thirty tests depend on in undocumented ways. Nobody can delete a row from it, so it only grows, and reading a test tells you nothing about why it passes.
Stubbing outbound HTTP
When the system under test calls someone else's API, the dependency belongs under your control. WireMock runs an HTTP server that you program:
class PricingClientTest {
@RegisterExtension
static WireMockExtension wiremock = WireMockExtension.newInstance()
.options(wireMockConfig().dynamicPort())
.build();
private PricingClient client;
@BeforeEach
void setUp() {
client = new PricingClient(wiremock.baseUrl(), Duration.ofMillis(500));
}
@Test
void readsThePriceFromTheResponseBody() {
wiremock.stubFor(get(urlPathEqualTo("/v1/prices/SKU-1"))
.withHeader("Accept", equalTo("application/json"))
.willReturn(okJson("""
{"sku":"SKU-1","amount":"24.00","currency":"EUR"}
""")));
assertThat(client.priceOf("SKU-1")).isEqualTo(Money.of("24.00", "EUR"));
wiremock.verify(getRequestedFor(urlPathEqualTo("/v1/prices/SKU-1"))
.withHeader("X-Request-Id", matching("[0-9a-f-]{36}")));
}
@Test
void failsFastWhenTheProviderIsSlow() {
wiremock.stubFor(get(anyUrl()).willReturn(ok().withFixedDelay(2_000)));
assertThatThrownBy(() -> client.priceOf("SKU-1"))
.isInstanceOf(PricingUnavailableException.class);
}
@Test
void retriesOnceOnA503() {
wiremock.stubFor(get(anyUrl()).inScenario("flaky")
.whenScenarioStateIs(STARTED)
.willReturn(serviceUnavailable())
.willSetStateTo("recovered"));
wiremock.stubFor(get(anyUrl()).inScenario("flaky")
.whenScenarioStateIs("recovered")
.willReturn(okJson("""
{"sku":"SKU-1","amount":"24.00","currency":"EUR"}
""")));
assertThat(client.priceOf("SKU-1")).isEqualTo(Money.of("24.00", "EUR"));
wiremock.verify(2, getRequestedFor(anyUrl()));
}
}
The failure scenarios are the point. Any client can be made to work against a happy-path stub; what breaks in production is the timeout that was never configured, the retry that hammered a struggling provider, the 500 that surfaced as a NullPointerException. WireMock's delays, fault injection and scenario state machine make those paths testable, and inspecting a captured request body is far easier with a formatted view — the JSON formatter is handy when a stub mismatch report is a single long line.
Messaging and asynchrony
Broker tests follow the same pattern with an extra difficulty: the result arrives later. Start the broker in a container, publish through your real producer, and poll for the outcome with a bounded wait rather than sleeping.
@Test
void publishesAnOrderPlacedEventConsumersCanRead() {
orderService.place(anOrder().withLine("SKU-1", 1, "24.00").build());
await().atMost(Duration.ofSeconds(5))
.untilAsserted(() -> {
List<OrderPlaced> received = testConsumer.drain();
assertThat(received).hasSize(1);
assertThat(received.getFirst().sku()).isEqualTo("SKU-1");
});
}
Thread.sleep(3000) in the same place would be both slower on a fast machine and flaky on a loaded CI runner. Also test the unhappy paths that only exist in messaging: a poison message that cannot be deserialised, a duplicate delivery that must be idempotent, and a consumer that fails midway and must not acknowledge.
Consumer-driven contracts
For service-to-service compatibility, contract testing replaces the shared end-to-end environment. The consumer declares what it needs; that declaration becomes a file; the provider verifies it.
@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "pricing-service", pactVersion = PactSpecVersion.V4)
class PricingContractTest {
@Pact(consumer = "checkout-service")
RequestResponsePact priceExists(PactDslWithProvider builder) {
return builder
.given("a price exists for SKU-1")
.uponReceiving("a request for the price of SKU-1")
.path("/v1/prices/SKU-1")
.method("GET")
.willRespondWith()
.status(200)
.body(new PactDslJsonBody()
.stringType("sku", "SKU-1")
.decimalType("amount", 24.00)
.stringMatcher("currency", "[A-Z]{3}", "EUR"))
.toPact();
}
@Test
@PactTestFor(pactMethod = "priceExists")
void theClientReadsThePrice(MockServer mockServer) {
PricingClient client = new PricingClient(mockServer.getUrl(), Duration.ofSeconds(1));
assertThat(client.priceOf("SKU-1")).isEqualTo(Money.of("24.00", "EUR"));
}
}
Two properties make this work. The consumer specifies matchers, not literal values — it needs a three-letter currency code, not specifically EUR — so the provider is free to change data without breaking the contract. And the given clause names a provider state that the provider's verification test sets up before replaying the request. Providers that add fields stay compatible; providers that remove or rename a field the consumer reads fail verification before deployment, which is exactly when you want to know. The design conventions that make an API easy to contract-test are the same ones covered in general API design guidance: stable field names, additive change, explicit versioning.
Keeping the cost down
Integration suites decay by minutes at a time. What actually helps:
- Start containers once. Per-class static containers, or one singleton for the whole suite. Per-method containers are the single most common cause of a twenty-minute build.
- Limit distinct configurations. Every unique combination of properties, profiles and overridden beans creates a separate application context that must be built from scratch.
- Run in parallel. Enable JUnit's parallel execution and make tests independent enough to survive it; unique-data isolation and parallel execution reinforce each other.
- Split the suite. Fast unit tests on every commit, integration tests on merge, the slowest end-to-end journeys nightly. Naming conventions (
*Testversus*IT) let the build tool separate them without annotations. - Use small images. Alpine variants and pre-warmed images cut seconds off every start.
- Delete tests that no longer earn their runtime. A test that has never failed for a real reason in two years, duplicating what three others cover, is a liability.
When integration tests turn flaky
A test that fails intermittently destroys more value than it creates, because the team learns to re-run rather than investigate. In integration suites the causes are predictable: shared state left by a previous test, a fixed port that collides under parallel execution, a wait that assumed a timing, a dependency on today's date, an ordering assumption about rows a query returned without ORDER BY, or a container that was accepting connections before it was ready.
Treat every one as a defect in the test, not as background noise. Reproduce it by running the suite repeatedly, in a random order, on a loaded machine — the conditions under which it fails are information about the cause. The policy that keeps this from sliding is described in the test automation strategy guide: quarantine, ticket, fix within a fixed window, or delete.
Key takeaways
- Decide what boundary each test covers before writing it; a test whose failure could mean anything diagnoses nothing.
- Test persistence against the real engine with the real migrations — Testcontainers removed the reason to substitute an in-memory database.
- Choose one isolation strategy — rollback, truncate or unique data — and apply it everywhere; unique data is the one that survives parallel execution.
- Build setup data with builders and object mothers, not a shared fixture file that only ever grows.
- Stub outbound HTTP with WireMock and spend most of the effort on timeouts, retries and error responses rather than the happy path.
- Replace cross-service end-to-end suites with consumer-driven contracts, which verify compatibility without both services running at once.
Sources and further reading
Frequently asked questions
- Why not use H2 instead of a container for database tests?
- Because an in-memory database is a different product. H2 in a compatibility mode still differs from PostgreSQL or Oracle in type handling, JSON support, window function coverage, locking behaviour, sequence allocation, upsert syntax and error codes. A suite that passes on H2 and fails on the real engine is worse than no suite, because it produced confidence that was not earned. Containers made the substitution unnecessary.
- How do I stop integration tests interfering with each other?
- Pick one strategy and apply it consistently. Transactional rollback is fastest but hides commit-time behaviour and does not work across process boundaries. Truncating tables between tests is slower but honest. Generating unique keys per test so that data simply does not collide is often the best of both and works with parallel execution. What never works is assuming the previous test cleaned up after itself.
- What does a consumer-driven contract test actually verify?
- Two halves. On the consumer side, the test runs your client against a mock server built from the expectations you declared, producing a contract file that records the requests you make and the response fields you rely on. On the provider side, a separate test replays those requests against the real provider and checks the responses still satisfy them. Together they prove compatibility without ever deploying both services into one environment.
- Are integration tests supposed to be slow?
- Slower than unit tests, yes; slow in absolute terms, no. The dominant costs are container start-up and context creation, both of which are fixable — reuse a static container across the whole suite, keep the number of distinct configurations small, run classes in parallel and use the smallest usable images. A well-tuned suite of a couple of hundred database-backed tests finishing in two or three minutes is a realistic target.