Spring Boot database testing with Testcontainers

Integration tests often expose problems that mocked repositories conceal: malformed SQL, incompatible column types, broken transactions, and migration errors. This guide to Spring Boot testing with Testcontainers for database integration replaces those mocks with disposable, production-like database instances while keeping each test repeatable.

Testcontainers starts the actual database engine in a Docker container, allowing Spring to apply the required schema before the test and clean up the instance afterwards. The result is faster feedback than a manually managed test server and stronger confidence for Spring JDBC, Spring Data JPA, and Hibernate applications.

Preparing the test environment

Add Testcontainers and Spring Boot’s test-container support to the test scope. Let Spring Boot’s dependency management align the Testcontainers version:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-testcontainers</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>junit-jupiter</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>postgresql</artifactId>
    <scope>test</scope>
</dependency>

Docker must be available to the test process. Developers connecting from a Brisbane CBD office or working from home can use Docker Desktop, Colima, or another compatible local engine. A stopped Docker socket, an architecture mismatch on an ARM-based Mac, or corporate security policies can fail the suite before Spring starts.

Connecting the application context

With Spring Boot 3.1 or later, @ServiceConnection supplies the container’s URL, username, password, and driver to the application context:

@Testcontainers
@SpringBootTest
class OrderRepositoryTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> postgres =
            new PostgreSQLContainer<>("postgres:16-alpine");

    @Autowired
    OrderRepository orders;
}

For an earlier release or custom setup, expose the same values through @DynamicPropertySource. Keep one connection strategy per test class. Pin the image to the database edition and compatible patch level used in staging or production because SQL dialect and locking behaviour can differ between versions.

Exercising repositories and services

A repository test can now save an order, call flush, clear the persistence context, and reload it. Assertions then cover generated keys, mappings, cascades, query results, and constraint failures rather than mocked return values. JDBC tests can use JdbcTemplate to verify affected rows, while controller tests can exercise JSON contracts and authentication filters against persisted records.

Use @Transactional for fast rollback, but remember that it does not erase data committed through another connection. Avoid sharing mutable state between tests, and give parallel methods separate schemas or databases. Flyway or Liquibase migrations should run through the same Spring Boot configuration as production so migration defects are included in every test cycle.

Creating safe and realistic test data

Build fixtures with SQL scripts or JdbcTemplate, then keep each dataset small and purposeful. Synthetic Australian addresses, mobile-number formats, and names make assertions readable without handling real personal information. Production extracts should never be copied into a development laptop or CI artefact, especially when they may contain health, financial, or identity data.

Australian businesses covered by the Privacy Act 1988 must handle personal information consistently with the Australian Privacy Principles, while eligible data breaches may trigger reporting under the Notifiable Data Breaches scheme. The ACSC’s Essential Eight also supports safer development practices. Container isolation limits the blast radius, but it does not replace access controls, data minimisation, or secure deletion of test artefacts.

Running the suite in CI

On CI, choose a runner with Docker access and start the database container as part of the job. GitHub Actions, Bitbucket Pipelines, GitLab, and Azure DevOps can run these tests, but the worker operating system and CPU architecture must match the container image. Cache images carefully, and avoid launching a fresh container for every assertion.

Engineering teams distributed across Sydney, Melbourne, Brisbane, and Perth often use hybrid work, so local failures should be reproducible on a managed runner. Australian-hosted AWS or Azure regions can reduce latency, yet spinning up cloud infrastructure for routine tests adds AUD charges and complexity. A reusable container per build usually provides a sensible balance between isolation, speed, and cost.

Recommendations for reliable integration suites

A dependable suite depends on predictable configuration, representative data, and disciplined lifecycle management:

Run fast repository tests during local development and the full integration suite before merging. Recording each failure category helps teams in Australian engineering offices improve reliability without turning every red build into a meeting. A disposable, version-matched database turns integration testing into a repeatable engineering practice rather than a source of flaky results.