Sub topic 10
Testing against a real database with Testcontainers
This chapter assumes you can write a Spring Data JPA repository, you know what a slice test is, and you have used @DataJpaTest before. You also need Docker running on your machine.
Why not an embedded database
By default, @DataJpaTest replaces your DataSource with an embedded database such as H2. That is fast, but H2 is not PostgreSQL. SQL dialect differences, native queries, JSON columns, and Flyway or Liquibase scripts written for PostgreSQL can pass on H2 and fail in production, or the reverse.
Testcontainers is a Java library that starts throwaway Docker containers from test code. You run the same database engine you use in production, and the container is removed when the tests finish.
Add the dependencies
With Gradle, add the Testcontainers JUnit 5 integration, the PostgreSQL module, and the Spring Boot integration:
dependencies {
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.boot:spring-boot-testcontainers'
testImplementation 'org.testcontainers:junit-jupiter'
testImplementation 'org.testcontainers:postgresql'
runtimeOnly 'org.postgresql:postgresql'
}Spring Boot manages the Testcontainers versions, so you do not need to pin them.
A repository test with a container
@DataJpaTest
@Testcontainers
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class GreetingRepositoryTest {
@Container
@ServiceConnection
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");
@Autowired
GreetingRepository repository;
@Test
void findsGreetingByName() {
repository.save(new Greeting("Ada", "Hello, Ada"));
assertThat(repository.findByName("Ada")).isPresent();
}
}Each annotation does one job:
| Annotation | Purpose |
|---|---|
| `@DataJpaTest` | Loads only the JPA layer: entities, repositories, and a transaction manager. |
| `@Testcontainers` | Enables the JUnit 5 extension that starts and stops containers. |
| `@Container` | Marks the field as a container managed by that extension. |
| `@AutoConfigureTestDatabase(replace = NONE)` | Stops Spring from swapping in an embedded database. |
| `@ServiceConnection` | Reads the container's host, port, and credentials and configures the `DataSource` from them. |
The container field is static, so one container serves every test method in the class. A non-static field starts a new container for each test, which is much slower.
How the pieces connect
The container listens on a random host port, so you never hard-code a JDBC URL. @ServiceConnection is why you do not need one. It replaces the older approach of writing a @DynamicPropertySource method that sets spring.datasource.url, username, and password by hand.
Common errors
- "Could not find a valid Docker environment." Docker is not running, or the current user cannot reach it. Start Docker and retry.
- Tests pass on H2 but the container test fails. This is the intended result. Fix the query or migration, not the test.
- Schema is empty. With the real database, Hibernate's default for non-embedded databases is
none, so no tables are created. Use Flyway or Liquibase, or setspring.jpa.hibernate.ddl-auto=create-dropin test properties. - Slow suite. Every class that declares its own container starts one. Share a container through a common base class or a shared configuration when many classes need the same database.
Exercise
Your @DataJpaTest with a PostgreSQLContainer still runs against H2, and the container starts but is never used. Which annotation is missing or wrong, and which one wires the container's connection details into the DataSource?
Show answer
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) is missing, so Spring replaces the DataSource with an embedded database. @ServiceConnection on the container field wires the container's host, port, and credentials into the DataSource.
Exercise
Why should the @Container field usually be static?
Show answer
A static container starts once per test class and is shared by all its test methods. A non-static container starts again for every test method, which makes the class much slower.