Integration Tests with Testcontainers: A Real PostgreSQL for Every Spring Boot Test Run
The Ticket Desk ships on PostgreSQL, so its tests should run on PostgreSQL. A static PostgreSQLContainer with @Container and @ServiceConnection starts postgres:18 for the run, two tests save and read real rows (one through HTTP), and the container is removed afterwards.
What you will learn
- Explain why a green test on H2 proves less than one on PostgreSQL
- Add the Testcontainers test dependencies and a PostgreSQLContainer field
- Wire the container into Spring Boot with @ServiceConnection, no URL in any file
- Test a round trip from HTTP to a real row and back, and know where the time goes
Before you start
- Spring Boot Test Slices: @WebMvcTest and @DataJpaTest
- Docker installed and running
In production, the Ticket Desk runs on PostgreSQL. A common shortcut is to test with H2, an in-memory stand-in. The test goes green, but a green test on H2 only proves the stand-in works. A query that uses a PostgreSQL feature, or a column type H2 treats differently, can pass the test and fail in production.
Testcontainers fixes that. When the test runs, it starts a real PostgreSQL in a Docker container, the tests save and read real rows in it, and when the run is over the container is removed.
Four lines of setup
The pom needs the PostgreSQL driver plus three Testcontainers libraries:
postgresql: the driver the application uses.spring-boot-testcontainers: where Spring Boot meets Testcontainers, and where@ServiceConnectioncomes from.testcontainers-junit-jupiter: starts and stops containers around the tests.testcontainers-postgresql: thePostgreSQLContainerclass.
The three Testcontainers libraries are test scope, so the shipped application doesn't carry them. Docker has to be running on the machine that runs the tests.
The test class
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Testcontainers
class TicketDeskTest {
@Container
@ServiceConnection
static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:18");
@LocalServerPort
int port;
@Autowired
TicketRepository tickets;
@BeforeEach
void emptyDesk() {
tickets.deleteAll();
}
@Test
void repositoryFindsTicketsByStatus() {
tickets.save(new Ticket("Printer is jammed", "OPEN"));
tickets.save(new Ticket("Old laptop returned", "CLOSED"));
List<Ticket> open = tickets.findByStatus("OPEN");
assertThat(open).extracting(Ticket::getTitle).containsExactly("Printer is jammed");
}
@Test
void postedTicketComesBackFromPostgres() {
RestClient http = RestClient.create("http://localhost:" + port);
http.post().uri("/tickets").body(new TicketController.NewTicket("VPN keeps dropping"))
.retrieve().toBodilessEntity();
List<Ticket> open = http.get().uri("/tickets?status=OPEN").retrieve()
.body(new ParameterizedTypeReference<List<Ticket>>() { });
assertThat(open).extracting(Ticket::getTitle).containsExactly("VPN keeps dropping");
}
}
Each annotation has one job:
@SpringBootTest(webEnvironment = RANDOM_PORT)starts the whole application (controller, repository, Hibernate) on a random free port.@LocalServerPorttells the test which one.@Testcontainersswitches Testcontainers on, so JUnit looks for container fields.@Containersays JUnit owns this container: started before the tests, stopped after them.@ServiceConnectiontells Spring Boot to read the container's URL, user and password and use them as itsDataSource. There's no database URL in any file.
What happens behind the scenes
When you run mvn test, the Run window shows Testcontainers creating a container for the postgres image, starting it, and printing its JDBC URL. The container listens on a random free port on localhost, mapped to 5432 inside. Then Spring Boot starts, connected to it.
Before each test, deleteAll() empties the desk, so every test starts clean and the tests don't depend on each other. The first test saves an OPEN and a CLOSED ticket straight through the repository and reads back by status: only the OPEN one returns. The second goes over real HTTP: a POST opens "VPN keeps dropping" (the controller saves it as OPEN), and a GET by status finds that same row.
Start once, test twice
| Step | Time (this run) |
|---|---|
| Container start | 2.8 s |
| Spring Boot start | 8.37 s |
repositoryFindsTicketsByStatus | 1.86 s |
postedTicketComesBackFromPostgres | 0.63 s |
Two tests run, no failures. Most of the time goes into the first two rows, and you pay for them once for the whole class. The static keyword on the container field is what makes it shared; without it, JUnit would start a fresh container for every test method. Your times will differ, but the shape won't.
Common mistakes
- A non-static container field. One container per test method, and the suite crawls.
- Hard-coding
localhost:5432in a test profile. The container's port is random. Let@ServiceConnectionsupply it. - Tests that depend on each other's rows. Clean up in
@BeforeEach. - Docker not running. The test fails before Spring even starts. Check Docker first.
Try it yourself
Use postgres:17 instead of postgres:18 and run again. Do both tests still pass? This is how you check a database upgrade before it reaches production.
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Unit Tests With AI for a Spring Boot Service: Mockito Mocks, Given-When-Then and a Green Run
CommentServiceTest runs the real CommentService with three Mockito mocks for its repositories: no Spring, no database, five tests in a fraction of a second. An AI drafts it from a short prompt; we read each test, run it, and learn to read the red message when an expectation is wrong.
Docker for a Spring Boot App: Run the Tests in the Image Build, or Skip Them on Purpose
The blog's Dockerfile runs mvnw package with -DskipTests=${SKIP_TESTS}, false by default, so every docker build runs all 53 tests and a red one means no image. --build-arg SKIP_TESTS=true cuts the package step from 41 to 23 seconds, which is only safe after CI has run the tests.
The Test Pyramid in Spring Boot: Unit, Slice and Whole-App Tests
One small ticket desk, three kinds of test: four plain unit tests in 20 ms, two @WebMvcTest slice tests in 4.4 s, one @SpringBootTest flow in 711 ms. Where each rule belongs, and what you should never test at all.
Mockito and Test Doubles: Stubs, Mocks and Fakes for One Java Class
Test TicketService.close on its own: a stub repository that answers findById, a mock notifier that records send, verify to check both calls, and a HashMap fake that really stores the closed ticket.
