Quick revision
The short answer
We annotate the test class with @DataJpaTest (or @SpringBootTest) and @Testcontainers, and declare @Container @ServiceConnection static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17-alpine"). @ServiceConnection, available since Spring Boot 3.1, builds the connection details from the container, so no datasource properties are needed. With @DataJpaTest we add @AutoConfigureTestDatabase(replace = Replace.NONE) where the version would otherwise swap in an embedded database, and we keep the container static so it starts once per class rather than once per test.
What to remember
In this answer, we wrote a repository test against a real PostgreSQL using @DataJpaTest, @Testcontainers and a static @Container @ServiceConnection PostgreSQLContainer. @ServiceConnection, since Spring Boot 3.1, builds the connection details from the container so no datasource properties are needed. We switched off the embedded database replacement with @AutoConfigureTestDatabase(replace = Replace.NONE), used saveAndFlush() to make the database enforce constraints, and saw that a static container starts once per class while an instance container restarts for every test.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We annotate the test class with @DataJpaTest (or @SpringBootTest) and @Testcontainers, and declare @Container @ServiceConnection static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17-alpine"). @ServiceConnection, available since Spring Boot 3.1, builds the connection details from the container, so no datasource properties are needed. With @DataJpaTest we add @AutoConfigureTestDatabase(replace = Replace.NONE) where the version would otherwise swap in an embedded database, and we keep the container static so it starts once per class rather than once per test.
Why this question is asked
Repository tests are where mocks help least and real databases help most: SQL syntax, column mappings, constraints and query plans are exactly the things a mock cannot check. Testcontainers makes a real PostgreSQL as easy to use as an in-memory database, and @ServiceConnection removes the last bit of wiring. Interviewers ask for this code to see whether we know the pieces and the traps, especially the embedded database replacement and the container lifecycle. In this answer, we will set up the dependencies, write the test step by step, understand what each annotation does, look at the database replacement trap, and see how static and instance containers differ.
1The Dependencies
We need three things on the test classpath: Spring Boot's test support, Spring Boot's Testcontainers integration, and the Testcontainers PostgreSQL module, plus the PostgreSQL JDBC driver at runtime. With Spring Boot's dependency management, versions are aligned for us.
Module and package names have shifted in recent releases: Testcontainers 2 renamed its artifacts (for example testcontainers-postgresql) and moved the container classes, and Spring Boot 4 split test slices into separate modules. Check your versions; the structure of the test stays the same.
2Writing the Repository Test
Here is a complete test for an OrderRepository with a derived query and a custom JPQL query. It starts a real PostgreSQL in Docker, runs Flyway or Hibernate schema creation against it, and runs the queries for real.
Notice saveAndFlush() in the second test. @DataJpaTest runs each test in a transaction that is rolled back at the end, so without a flush Hibernate might never send the INSERT, and the constraint would never be checked. Flushing forces the SQL to the database inside the test. The rollback at the end also keeps the tests independent: the rows from one test are gone before the next one starts.
3What Each Annotation Does
@DataJpaTest starts a slice of the application: JPA, Hibernate, Spring Data repositories, the DataSource and Flyway or Liquibase if present, but no web layer and no other services. It is much faster to start than @SpringBootTest and makes every test transactional with rollback.
@Testcontainers is a JUnit 5 extension from Testcontainers. It finds fields annotated with @Container and manages their lifecycle: starting them before they are needed and stopping them afterwards.
@ServiceConnection, from Spring Boot 3.1, tells Spring Boot to create connection details from the container. For a PostgreSQLContainer it creates a JdbcConnectionDetails bean with the container's JDBC URL, username and password, and the DataSource auto-configuration uses those instead of the spring.datasource properties. That is why the test needs no properties at all, even though the port is random on every run.
7 messages in order. Play them, or step through them one at a time.
4The Embedded Database Trap
By default, @DataJpaTest includes @AutoConfigureTestDatabase, which tries to replace the application's DataSource with an embedded in-memory database such as H2 if one is on the classpath. That was a sensible default before containers were cheap, but here it would defeat the purpose: our test would quietly run on H2, not PostgreSQL, and PostgreSQL-specific SQL, types such as jsonb, or constraint behaviour would not be tested. If no embedded database is on the classpath, the replacement fails instead.
Setting replace = Replace.NONE switches the replacement off, so the DataSource built from the container's connection details is used. In some recent Spring Boot versions, the replacement already backs off when a @ServiceConnection provides the connection; check your version. Keeping the annotation explicit costs nothing and documents the intent.
5Static or Instance Container
Where we declare the container decides how often it starts. A static @Container field is started once before the first test of the class and stopped after the last one, so all tests in the class share one database. An instance field is started and stopped for each test method, which gives perfect isolation but costs a few seconds per test.
For repository tests, static is almost always right, because the transaction rollback already isolates the tests. A static container also works well with Spring's context cache: the context is built once against that container and reused. With an instance container, each test would have a different URL, which does not fit a cached context. To share one container across many test classes, the next step is a singleton container in a base class or a @TestConfiguration that declares the container as a bean.
| Declaration | Starts | Fits |
|---|---|---|
static @Container field | once per test class | repository tests, cached contexts |
instance @Container field | once per test method | tests that need a fresh server |
| singleton in a base class or bean | once per JVM | large suites with many classes |
6Follow-up questions
Do I need to use the same PostgreSQL version as production?
Yes, as closely as possible. Pinning the image tag, for example postgres:17-alpine, to the production major version means the tests check the same SQL dialect, functions and planner behaviour that production uses.
Can I use @SpringBootTest instead of @DataJpaTest?
Yes. The container and @ServiceConnection work the same way, and no database replacement happens. The test then starts the whole application, which is slower and is better kept for tests that need more than the data layer.
Why does a test see no rows that another test inserted?
Because @DataJpaTest rolls back each test's transaction. That isolation is intended. Data that must exist for every test should come from a migration or a setup method inside the test's transaction.
7Conclusion
In this answer, we wrote a repository test against a real PostgreSQL using @DataJpaTest, @Testcontainers and a static @Container @ServiceConnection PostgreSQLContainer. @ServiceConnection, since Spring Boot 3.1, builds the connection details from the container so no datasource properties are needed. We switched off the embedded database replacement with @AutoConfigureTestDatabase(replace = Replace.NONE), used saveAndFlush() to make the database enforce constraints, and saw that a static container starts once per class while an instance container restarts for every test.
Open with
I would annotate the test class with @DataJpaTest and @Testcontainers, and declare a static field annotated with @Container and @ServiceConnection: a PostgreSQLContainer with an image tag that matches production, for example postgres:17-alpine. @Testcontainers starts and stops the container, and because the field is static it starts once for the whole class instead of once per test. @ServiceConnection, available since Spring Boot 3.1, makes Boot build JdbcConnectionDetails from the container's URL, username and password, so I need no datasource properties even though the port is random on each run.
Then, if they want more
With @DataJpaTest I also add @AutoConfigureTestDatabase with replace set to NONE, because by default the slice may replace my DataSource with an embedded database like H2, and then I would not be testing PostgreSQL at all; some recent versions back off automatically, but being explicit is harmless.
Each test runs in a transaction that rolls back, which keeps tests independent, and when I want the database to check a constraint I use saveAndFlush so the SQL is actually sent. If many classes need the database, I would move the container to a shared singleton so the whole JVM uses one.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Boot 3.1, JUnit 5, PostgreSQL 17, Spring Boot 4
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- JUnit user guide, Mockito documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Show how to run a Spring Boot repository test against a real PostgreSQL using...": https://scrivio-interview-library.netlify.app/java/integration-testing/7b7c33c42a/