Sub topic 9
Testing repositories with @DataJpaTest
This chapter assumes you can write a Spring Data JPA repository, you know what an entity is, and you have read the earlier chapters on test slices and spring-boot-starter-test. Testcontainers gets its own chapter, so here it appears only as the database provider.
What a repository test should prove
Spring Data generates repository implementations at runtime. Your code is often only an interface with derived query methods such as findByName. A mock-based unit test cannot show that those queries work. The risks are in the mapping and the SQL: a wrong column name, a misspelled property in a method name, or a query that behaves differently on your production database.
@DataJpaTest is a test slice for this layer. It loads only JPA-related auto-configuration: entities, repositories, the DataSource, and EntityManager. Controllers, services, and other beans are not created, so the test starts faster than a full @SpringBootTest.
What the slice gives you
- Each test method runs in a transaction that rolls back when the test ends, so tests do not leave data behind for each other.
- A
TestEntityManagerbean is available for setting up data. - By default, the slice replaces your configured
DataSourcewith an embedded database, if one is on the classpath.
The last point is a common source of false confidence. An in-memory database such as H2 can accept SQL that PostgreSQL rejects, and the reverse. To test against the database you run in production, turn the replacement off.
A repository test against PostgreSQL
The example below uses a PostgreSQL container started by Testcontainers. @ServiceConnection points the DataSource at that container, so you do not set a URL or password.
@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 has one job:
| Annotation | Purpose |
|---|---|
| `@DataJpaTest` | Loads only the JPA slice and wraps each test in a rolled-back transaction |
| `@Testcontainers` | Starts and stops the fields marked `@Container` |
| `@AutoConfigureTestDatabase(replace = NONE)` | Keeps your real `DataSource` instead of an embedded one |
| `@ServiceConnection` | Configures the `DataSource` from the running container |
Flush before you assert
The example above has a weakness. save may only queue the insert in Hibernate's persistence context. findByName triggers a query, so Hibernate flushes pending changes first, and this test works. In other cases the SQL never runs inside the test. For example, a constraint violation will not appear until a flush.
@Autowired
TestEntityManager entityManager;
@Test
void rejectsDuplicateNames() {
entityManager.persist(new Greeting("Ada", "Hello, Ada"));
entityManager.flush();
entityManager.clear();
assertThat(repository.findByName("Ada")).isPresent();
}flush() sends the SQL to the database. clear() empties the persistence context, so the next read goes to the database instead of returning the cached entity object.
Common errors
- Using H2 by accident. If you omit
replace = NONE, the test runs on the embedded database and can pass while production fails. - Asserting on cached entities. Without
clear(), a read can return the object you just saved, so the mapping is never checked. - Missing constraint failures. Without
flush(), a violated constraint is not detected before the transaction rolls back. - Testing Spring Data itself. Methods like
saveandfindByIdare already tested by the framework. Test your derived queries,@Querymethods, and entity mappings. - Expecting service beans. The slice does not load
@Serviceclasses. Import what you need with@Import.
Exercise
A repository test saves an entity with a unique-name constraint, then saves a second entity with the same name, and expects an exception. The test passes without any exception. Why can this happen, and how do you fix it?
Show answer
The inserts are queued in the persistence context and never sent to the database, because the test transaction rolls back at the end. Call flush() on the repository (saveAndFlush) or on TestEntityManager after the second save so the SQL runs and the constraint fires.
Exercise
Why do you add @AutoConfigureTestDatabase(replace = NONE) when using a Testcontainers PostgreSQL container with @DataJpaTest?
Show answer
By default @DataJpaTest replaces the DataSource with an embedded database. Setting replace to NONE keeps the DataSource that @ServiceConnection configured, so the test runs against real PostgreSQL.