Skip to content

    System Design

    Integration Testing with Testcontainers

    Learn how Testcontainers runs a real PostgreSQL for Spring Boot integration tests, and what an H2 stand-in can and cannot prove when Docker is not available.

    By Published 12 min read

    Share

    Standard lessonintermediateSpring Boot labBackend System Design

    Before this: The Testing Pyramid for Backend Systems

    What you'll learn: By the end of this lesson you will be able to explain what Testcontainers does and what it needs, wire a real PostgreSQL into a Spring Boot test with @ServiceConnection, write the database tests once and run them against more than one database, and say precisely what an in-memory H2 stand-in can and cannot prove.

    Picture an aircraft maker testing a new wing. A scale model in a wind tunnel is quick and cheap, and it catches many mistakes. It does not tell you how the real wing behaves in real air, so before certification someone flies the real thing. An in-memory database is the scale model; a throwaway PostgreSQL started for the test is the real wing on a short flight.

    An honest note before the lesson starts. Testcontainers needs a Docker-compatible container runtime, and the machine that produced this lesson's lab has none. So the Testcontainers test in this lesson was compiled but never run. What did run is the same test suite against H2 in memory, plus a probe of what H2 does with PostgreSQL-flavoured SQL. The lesson says which is which at every step.

    This builds on The Testing Pyramid for Backend Systems, which explains why one test level needs a real database. Contract testing and load testing are separate later lessons.

    Verified with Spring Boot 4.1.2, Java 25, H2 2.4.240, the Testcontainers for Java 2.0.5 documentation and the PostgreSQL 18 documentation, on 2026-12-01. The Testcontainers code was read from the documentation and compiled; it was not run.

    The core idea

    Testcontainers starts a real, disposable service in a container for the duration of a test, so the integration test talks to the same kind of database production uses. Where that is impossible, a stand-in such as H2 can run the same tests, but every result from a stand-in is a statement about the stand-in until a real database has agreed.

    Three illustrations run through the lesson:

    • Minimal example: a three-test contract on an order store, run on H2 in the lab.
    • Realistic example: ShopStream's order write, which needs an idempotency key, a stock guard and one transaction.
    • Failure example: PostgreSQL-flavoured SQL that H2 rejects or accepts differently, from the lab's probe.

    What Testcontainers does

    The Testcontainers documentation describes the library as one that supports JUnit tests and provides "lightweight, throwaway instances of common databases". It lists Docker as the prerequisite and a supported test framework (JUnit 4, JUnit 5 or Spock), or manual lifecycle control. A test declares a container, the library starts it before the test, hands over its connection details and stops it afterwards.

    A test that starts its own PostgreSQLTest JVM to Testcontainers (declares); Testcontainers to Docker runtime (start); Docker runtime to PostgreSQL; Test JVM to PostgreSQL (JDBC)Test JVM: JUnit, SpringTest JVMJUnit, SpringTestcontainers: libraryTestcontainerslibraryDocker runtime: daemonDocker runtimedaemonPostgreSQL: containerPostgreSQLcontainerdeclaresstartJDBC

    Figure 1. The test owns the database for its lifetime. How to read this: the library asks the container runtime to start a PostgreSQL; the test then connects to it over JDBC like any application would. The runtime is outside the test's control, which is why its absence stops the test.

    The runtime requirement is real. The documentation asks for "a Docker-API compatible container runtime", such as a local Docker install or Testcontainers Cloud, and says Colima, Podman and Rancher Desktop are alternatives that "are not actively tested in the main development workflow", so not every feature may work. Testcontainers discovers the daemon through environment settings such as DOCKER_HOST; if none is reachable, the test cannot start its container.

    The lifecycle, in JUnit 5

    With the JUnit 5 extension, @Testcontainers on the class and @Container on a field manage the container. A static field is shared between test methods: started once before the first test and stopped after the last. An instance field is started and stopped for every test method. The documentation also notes that the extension "has only been tested with sequential test execution", so parallel execution is not supported.

    Wiring it into Spring Boot

    Spring Boot's @ServiceConnection turns a container into a connection: with the spring-boot-testcontainers module on the test classpath, a PostgreSQLContainer produces the JDBC (and R2DBC) connection details bean that Spring Boot's auto-configuration then uses, and those details "take precedence over any connection-related configuration properties". The alternative is a static @DynamicPropertySource method that adds properties such as the URL to the Spring Environment, which is "slightly more verbose but also more flexible".

    This is the lab's PostgreSQL test. It is compiled by the lab and not run here:

    @Testcontainers
    @SpringBootTest
    class PostgresOrderStoreTest extends OrderStoreContract {
    
        @Container
        @ServiceConnection
        static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:18");

    The test-scope dependencies are spring-boot-testcontainers, testcontainers-junit-jupiter and testcontainers-postgresql, plus the PostgreSQL JDBC driver; the documentation warns that the Testcontainers module does not add a driver. In the lab's Gradle build their versions come from Spring Boot's dependency management, which resolved Testcontainers 2.0.5.

    One lifecycle trap is documented. Containers in static fields are stopped after the test class, but Spring's test framework may cache the application context beyond that point, and the Spring Boot documentation recommends managing containers as Spring beans or importing container declarations in that case. Containers declared as beans are started once per application context and stopped with it. The Testcontainers documentation also describes the singleton pattern, in which a base class starts a container in a static block and every subclass reuses it, with the Ryuk helper container stopping it when the suite ends.

    Write the tests once

    The practical pattern is a contract: an abstract class holds the tests, and each database gets a thin subclass that supplies the Spring context.

    classDiagram accTitle: One contract, two database variants accDescr: The abstract class OrderStoreContract holds three tests. H2OrderStoreTest extends it and runs on an in-memory H2 database. PostgresOrderStoreTest extends it and runs on a PostgreSQL container started by Testcontainers. class OrderStoreContract { +anOrderAndItsStockChangeCommitTogether() +aRepeatedIdempotencyKeyIsRecordedOnce() +aRefusedOrderLeavesNoOrderRowBehind() } class H2OrderStoreTest { H2 in memory runs in the lab } class PostgresOrderStoreTest { PostgreSQL container compiled, not run } OrderStoreContract <|-- H2OrderStoreTest OrderStoreContract <|-- PostgresOrderStoreTest

    Figure 2. One set of assertions, two databases. How to read this: the arrows point to the parent. Both subclasses inherit the same three tests; only the database underneath changes.

    The contract is small on purpose. Each test checks a behaviour that lives in the database and the transaction, the part that the lesson on the testing pyramid showed fakes cannot check:

    @Test
    void aRefusedOrderLeavesNoOrderRowBehind() {
        assertThatThrownBy(() -> service().place("k-2", "milk-1l", 9)).isInstanceOf(OutOfStockException.class);
        assertThat(store().stock("milk-1l")).isEqualTo(5);
        assertThat(store().orderCount()).isZero();
    }

    What a stand-in can and cannot prove

    H2 is a fast database that runs inside the test JVM. H2's documentation describes PostgreSQL emulation as a compatibility mode switched on in the URL (MODE=PostgreSQL), and says plainly that only "a small subset of the differences between databases are implemented in this way". The lab measures what that means for a handful of statements.

    flowchart TD accTitle: Choosing a database for an integration test accDescr: A decision flow. If production-specific SQL or behaviour is under test and a container runtime is available, use Testcontainers with the production database image. If no container runtime is available, run the portable subset on H2 and run the database-specific tests in CI where a runtime exists. If the SQL is fully portable and fast feedback matters, H2 is acceptable for that subset. A["An integration test needs a database"] --> B{"Does it use database-specific SQL or behaviour?"} B -- "yes" --> C{"Is a container runtime available?"} C -- "yes" --> T["Testcontainers with the production image"] C -- "no" --> CI["Run it in CI where a runtime exists"] B -- "no, portable SQL only" --> H["H2 in memory is acceptable, plus a periodic run on the real database"]

    Figure 3. Pick the database from what the test needs to be true. How to read this: database-specific behaviour forces the real database; portable SQL can use a stand-in, provided the real one is run somewhere too.

    Here is the PostgreSQL side of the comparison, from the PostgreSQL 18 documentation: jsonb ->> text extracts a JSON field as text; ON CONFLICT DO NOTHING "simply avoids inserting a row", and for DO NOTHING the conflict target is optional; SKIP LOCKED skips rows that cannot be locked immediately, which the documentation warns gives "an inconsistent view of the data" and suits queue-like tables; and unquoted names are "always folded to lower case". The lab sends these constructs to H2.

    Build it: the contract on H2, and a dialect probe

    Goal. Run the contract where no Docker exists, and measure how far H2 follows PostgreSQL.

    Setup. From the repository's examples/spring-labs folder:

    ./gradlew :labs:integration-test-standins:test

    The task runs the three-test contract on H2, in memory (H2OrderStoreTest), three probe tests and a golden-file comparison. The code is in examples/spring-labs/labs/integration-test-standins/. The PostgreSQL variant lives in a separate source set, so test and check never need Docker; ./gradlew :labs:integration-test-standins:compileContainerTestJava compiles it, and a task named containerTest would run it on a machine with a container runtime. That task was not run.

    What the lab does instead of Testcontainers, plainly: the same assertions run against H2 in its default mode (the contract), and a separate probe sends PostgreSQL-flavoured statements to H2 in default mode and in MODE=PostgreSQL.

    The schema uses only portable SQL (a primary key, a unique column, an identity column), and the store's update carries its own guard:

    public boolean reserve(String sku, int quantity) {
        return jdbc.sql("update stock set quantity = quantity - ? where sku = ? and quantity >= ?")
                .params(quantity, sku, quantity)
                .update() == 1;
    }

    Expected output, captured from a real run (Java 25, Spring Boot 4.1.2, H2 2.4.240, 2026-12-01):

    Part 1. The contract tests' scenarios on H2 (in memory). Start state: stock(milk-1l)=5, orders=0.
    1 place(k-1, milk-1l, 2)                             -> PLACED                  stock=3 orders=1
    2 place(k-1, milk-1l, 2) again, same key             -> DUPLICATE               stock=3 orders=1
    3 place(k-2, milk-1l, 9), only 3 on hand             -> OutOfStockException     stock=3 orders=1
    
    Part 2. PostgreSQL-flavoured statements sent to H2 (accepted = H2 parsed and ran it).
    statement                          H2 default mode        H2 MODE=PostgreSQL
    P1 ON CONFLICT DO NOTHING          rejected (42000)       accepted
    P2 ON CONFLICT (k) DO NOTHING      rejected (42000)       rejected (42000)
    P3 cast to jsonb                   rejected (HY004)       accepted
    P4 jsonb ->> operator              rejected (HY004)       rejected (42000)
    P5 gen_random_uuid()               rejected (90022)       accepted
    P6 FOR UPDATE SKIP LOCKED          accepted               accepted
    P7 current_setting()               rejected (90022)       rejected (90022)
    P8 date_trunc('day', now())        accepted               accepted
    column label of: select 1 as Total TOTAL                  total
    Row What it shows
    1 An order and its stock change commit together (stock 3, one order).
    2 A repeated idempotency key is recorded once: no second order, no second stock change.
    3 A refused order rolls back its order row: orders=1 is still the first order only.
    P1 ON CONFLICT DO NOTHING without a target is rejected by default H2 and accepted in PostgreSQL mode.
    P2 ON CONFLICT (k) DO NOTHING, with a conflict target, is rejected in both modes of this H2 version.
    P3, P5 The jsonb cast and gen_random_uuid() appear only in PostgreSQL mode.
    P4 The ->> operator on jsonb is rejected even in PostgreSQL mode.
    P6, P8 Accepted in both: syntax acceptance only; the lab does not show that the behaviour matches PostgreSQL.
    P7 current_setting() is unknown to both.
    Last The label of an unquoted alias is TOTAL by default and total with the lab's PostgreSQL-mode URL, which also sets DATABASE_TO_LOWER=TRUE. PostgreSQL folds unquoted names to lower case.

    Read the table with care in both directions. A rejection (P4) means a test on H2 cannot even run that statement. An acceptance (P6) means only that it parsed and ran; whether it locks rows the way PostgreSQL does is something this lab cannot show.

    Break it. In OrderStore.reserve, delete and quantity >= ? and its third parameter. The contract test aRefusedOrderLeavesNoOrderRowBehind should fail on H2, because the update then succeeds with stock below zero. Restore the line and re-run the tests.

    Stretch. Write a second ON CONFLICT statement in a form PostgreSQL documents and see whether this H2 accepts it.

    What the lab leaves out. Every behaviour of a real PostgreSQL: locking, isolation under concurrent connections, planner choices, extensions, configuration. The container test is the part that would show them, and it did not run.

    Trade-offs

    Option Fidelity to production Speed Needs Wrong when
    Testcontainers with the production image High: the real engine Slower: starts a container; reuse across tests helps A container runtime Developers cannot run containers and no CI stage does
    H2 in memory (default mode) Low for vendor features Fast Nothing The code uses vendor-specific SQL
    H2 in MODE=PostgreSQL Partial; the vendor says a small subset Fast Nothing You treat acceptance as proof
    Shared test database High, but shared Fast to start A managed instance Tests interfere with each other
    Mocks only None for SQL Fastest Nothing The rule lives in the query

    In practice: ShopStream's order write

    This is the realistic example on the course's running example ShopStream; nothing in it describes a real company.

    This is a realistic scenario, not a case history.

    The situation

    The order write must be idempotent (a retried request creates one order), must never oversell, and must leave no order row when stock is short. The team's laptops run containers inconsistently, and the CI system can.

    Starting architecture

    ShopStream order store tests on laptops and in CIDeveloper laptop to Contract tests (test task); CI runner to Contract tests (both tasks); Contract tests to H2 (fast run); Contract tests to PostgreSQL (real run)Developer laptop: H2 in memoryDeveloperlaptopH2 in memoryCI runner: container runtimeCI runnercontainer runtimeContract tests: one abstract classContract testsone abstractclassH2: in processH2in processPostgreSQL: containerPostgreSQLcontainertest taskboth tasksfast runreal run

    Figure 4. The same contract on two databases. How to read this: laptops run the fast H2 variant; the CI runner runs both, so the real PostgreSQL run is the gate for merging.

    Options considered

    Option Laptop feedback Fidelity Risk
    A. H2 everywhere Fast Low Vendor behaviour is never tested
    B. Containers everywhere Slower High Laptops without a runtime cannot run the tests
    C. Contract on H2 locally, on PostgreSQL in CI Fast High at merge Two variants to keep in step

    The decision

    Option C. The contract lives in one abstract class so the variants cannot drift. Database-specific SQL is allowed only if it has a test in the PostgreSQL variant, and the merge gate is the CI run that includes it.

    Rollout and verification

    Add the container task to CI first and watch it pass on unchanged code. Then add a query that uses a PostgreSQL-only construct and check that the laptop variant cannot run it and says so, rather than silently skipping it. Track how often the CI run fails where the laptop run passed: each such failure is a stand-in lie that was caught.

    The 2 a.m. failure

    The page reads: duplicate orders after a retry storm. A change replaced the portable insert with ON CONFLICT for speed; the H2 variant accepted it in PostgreSQL mode, but nobody had added a PostgreSQL-variant test and the CI task was marked optional. Checks: count orders with the same idempotency key, and read the deployed statement. Mitigation: remove the duplicates by hand and roll back. The lasting fix is to make the container task required, and a test that fires two identical requests concurrently on the real database. This lab's H2 contract cannot show concurrency at all.

    Architect's notes

    • Name the database in the test. A test called "integration" should say whether it ran on H2 or PostgreSQL.
    • One contract, several databases. Subclass, do not copy.
    • Make the real-database run a gate. A check that is optional is a check that is skipped.
    • Reuse containers deliberately. A static field or a singleton avoids one start per test, and the cost is shared state; reset the data in @BeforeEach.
    • Use the production image tag. A different major version is a different database.

    Common mistakes

    • Trusting a green H2 run for vendor SQL. Acceptance is not equivalence.
    • A container in an instance field. It restarts for every test method.
    • Parallel test execution with the JUnit extension. The documentation says it was only tested sequentially.
    • A cached Spring context outliving a static container. Manage the container as a bean in that case.
    • Forgetting the JDBC driver. The Testcontainers module does not add one.

    Key takeaways

    • Testcontainers starts a real, throwaway service for a test and needs a Docker-compatible runtime.
    • @ServiceConnection wires the container into Spring Boot's connection details; @DynamicPropertySource is the more manual alternative.
    • Write database tests as a contract and run them on every database you rely on.
    • H2's PostgreSQL mode closes some gaps (here: ON CONFLICT without a target, jsonb cast, gen_random_uuid()) and leaves others (the ->> operator, ON CONFLICT with a target).
    • Without a container runtime, run the portable subset on a stand-in and the specific tests in CI, and say which is which.
    • The Testcontainers test in this lesson was compiled, not run.

    Practice exercises

    Exercise 1 (20 min). For each of P1 to P8, say whether a test that depends on the statement could run on H2, and whether a pass would prove PostgreSQL behaviour.

    Exercise 2 (45 min). Add a fourth contract test, "two different keys for the same sku both succeed while stock lasts", and run it on H2.

    Exercise 3 (1 hour). On a machine with a container runtime, run containerTest and compare its three results with the H2 run. Write down any difference.

    Exercise 4 (2 hours). Design a CI job for your own service that runs the contract on the production database image only when SQL files change, and argue whether that is safe.

    Contract testing with Pact and Spring Cloud Contract is a separate lesson later in this module.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments