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 Spring bean is, and you have used Gradle or Maven. It also assumes you have seen @DataJpaTest and that Docker (or a compatible container runtime) is installed on your machine. Testcontainers is a Java library that starts throwaway Docker containers from test code. In Spring Boot, it lets a repository test talk to the same kind of database you run in production.
Why not an embedded database
@DataJpaTest replaces your DataSource with an embedded database such as H2 by default. That is fast, but it is not your production database. The differences cause real bugs that pass in tests and fail in production:
- SQL dialect differences, for example
jsonbcolumns, array types, orON CONFLICTupserts that H2 does not support or handles differently. - Different locking, transaction isolation, and constraint behavior.
- Schema migrations written for PostgreSQL that cannot run on H2.
- Case sensitivity and sorting rules that differ between engines.
Testcontainers removes the gap. The test starts a real PostgreSQL server in a container, Spring connects to it, and the container is removed when the tests finish.
Adding the dependencies
You need the Spring Boot Testcontainers support, the JUnit 5 integration, the PostgreSQL module, and a JDBC driver. With Spring Boot 3.1 or later, the Boot BOM manages the Testcontainers versions for you.
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'
}
tasks.named('test') {
useJUnitPlatform()
}Each artifact has a job:
| Artifact | Purpose |
|---|---|
| `spring-boot-testcontainers` | Provides `@ServiceConnection` and the connection detail machinery |
| `org.testcontainers:junit-jupiter` | Provides `@Testcontainers` and `@Container` lifecycle handling |
| `org.testcontainers:postgresql` | Provides `PostgreSQLContainer` |
| `org.postgresql:postgresql` | The JDBC driver your application uses |
A repository test with a real PostgreSQL
This is the test from the chapter plan. Read each annotation, because each one solves one specific problem.
@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();
}
}@DataJpaTestloads only the JPA slice: entities, repositories, and aDataSource. Each test runs in a transaction that rolls back at the end.@AutoConfigureTestDatabase(replace = NONE)tells Spring not to swap in an embedded database. Without it, the test would silently use H2 and ignore your container.@Testcontainersactivates the JUnit 5 extension that finds@Containerfields and manages their lifecycle.@Containeron astaticfield starts the container once before the first test in the class and stops it after the last. On an instance field, a new container would start for every test method, which is slow.@ServiceConnectiontells Spring Boot to read the container's host, mapped port, username, and password and use them as theDataSourceconnection details. You do not writespring.datasource.urlanywhere.
The container's port is random. Docker maps the PostgreSQL port 5432 inside the container to a free port on the host, and @ServiceConnection hands that real port to Spring.
How the pieces connect
The order matters. The container must be running before Spring builds the context, because the context needs the connection details to create the DataSource. The Testcontainers JUnit extension guarantees this ordering for @Container fields declared in the test class.
Schema creation
A fresh PostgreSQL container has an empty database. Something must create your tables. You have three common choices:
- Let Hibernate generate the schema.
@DataJpaTestsetsspring.jpa.hibernate.ddl-autotocreate-dropfor embedded databases only. For a container, set it yourself with@DataJpaTest(properties = "spring.jpa.hibernate.ddl-auto=create-drop"). - Run Flyway or Liquibase migrations. If either is on the classpath, Spring Boot runs them against the container on startup. This is the best option because the test then verifies the same migrations that production uses.
- Provide a
schema.sqlscript, which Spring runs whenspring.sql.init.mode=always.
Prefer option 2 when you have migrations. A repository test that passes with Hibernate-generated tables can still fail in production if the migration scripts differ from the entity mappings.
@DataJpaTest(properties = "spring.jpa.hibernate.ddl-auto=create-drop")
@Testcontainers
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class GreetingSchemaTest {
@Container
@ServiceConnection
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");
@Autowired
GreetingRepository repository;
@Test
void persistsAndCounts() {
repository.save(new Greeting("Grace", "Hello, Grace"));
assertThat(repository.count()).isEqualTo(1);
}
}Sharing one container across test classes
A container takes a few seconds to start. If ten repository test classes each start their own, the suite pays that cost ten times. Move the container into a shared base class or a configuration class.
The recommended pattern with Spring Boot 3.1 and later is a @TestConfiguration that declares the container as a bean:
@TestConfiguration(proxyBeanMethods = false)
public class ContainersConfig {
@Bean
@ServiceConnection
PostgreSQLContainer<?> postgresContainer() {
return new PostgreSQLContainer<>("postgres:16");
}
}A test then imports it:
@DataJpaTest
@Import(ContainersConfig.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class GreetingRepositoryShareTest {
@Autowired
GreetingRepository repository;
@Test
void savesGreeting() {
repository.save(new Greeting("Linus", "Hello, Linus"));
assertThat(repository.findByName("Linus")).isPresent();
}
}Here Spring manages the container's lifecycle as a bean, so no @Testcontainers or @Container is needed. Because Spring caches the application context between test classes with the same configuration, all classes that import ContainersConfig with the same setup reuse one container.
Another option is a singleton container held in a static field of an abstract base class and started in a static block. That works with older Spring Boot versions, but you must start it yourself and rely on the JVM shutdown (handled by Testcontainers' Ryuk helper) to remove it.
Data isolation
@DataJpaTest rolls back each test's transaction, so data does not leak between test methods. With a shared container, this matters even more, because the database lives for the whole suite.
Rollback does not help in two cases:
- Tests that use
@SpringBootTestwith a real HTTP server. The request runs in a different thread and commits its own transaction, so the test's rollback cannot undo it. Clean up explicitly, for example withrepository.deleteAll()in an@AfterEachmethod. - Tests marked
@Transactional(propagation = NOT_SUPPORTED)or code that usesREQUIRES_NEW.
If you rely on auto-increment IDs or row counts, assert on values you created in the test, not on absolute numbers. A sequence in PostgreSQL does not roll back, so IDs keep growing across tests.
Common errors
- Could not find a valid Docker environment. Docker is not running or the current user cannot reach its socket. Start Docker and check
docker psworks from the same shell that runs Gradle. - The test uses H2 anyway. You forgot
@AutoConfigureTestDatabase(replace = NONE). Check the logs for the JDBC URL; it should bejdbc:postgresql://localhost:<port>/test. - Connection refused or timeouts at startup. Do not hard-code
localhost:5432. Use@ServiceConnectionor@DynamicPropertySource, which read the mapped port. @Containeron a non-static field starts a container per test. Make the fieldstaticunless you truly need isolation per method.- Tests pass locally but fail in CI. The CI runner may lack Docker, or an unpinned image tag such as
postgres:latestmay have changed. Pin the version, and match the version you run in production. @ServiceConnectionhas no effect. It needsspring-boot-testcontainerson the test classpath and Spring Boot 3.1 or later.
For Spring Boot versions before 3.1, use @DynamicPropertySource to copy the container's values into the Spring environment:
@DynamicPropertySource
static void datasourceProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}The method takes suppliers, not values, because the container has not started yet when Spring registers them. Spring calls the suppliers later, after the container is running.
Trade-offs
Container-based tests are slower than H2 tests and need Docker. A reasonable policy is to use them where database behavior matters: custom queries, native SQL, migrations, constraints, and locking. For simple CRUD that only exercises Spring Data's generated methods, a service-level unit test with a mocked repository is usually enough. Keep the number of container-backed test classes proportional to the amount of database-specific logic you have.
Exercise
A teammate writes a @DataJpaTest with a @Container @ServiceConnection static PostgreSQLContainer<?> field, but the test's log shows jdbc:h2:mem:... as the JDBC URL. What is missing, and why does it matter?
Show answer
The test needs @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE). By default, @DataJpaTest replaces the DataSource with an embedded database, so the container is started but never used. The test then runs against H2 and cannot catch PostgreSQL-specific problems.
Exercise
Your suite has eight repository test classes and each starts its own PostgreSQL container, which adds about 40 seconds. Name one way to reduce this and say what makes it work.
Show answer
Declare the container once as a @Bean with @ServiceConnection in a shared @TestConfiguration and import it into every test class. Spring caches the application context for classes with identical configuration, so the container starts once and is reused. A static singleton container in a base class also works.