Sub topic 17
Testing repositories with @DataJpaTest
This chapter assumes you know how to map entities with @Entity, define a Spring Data repository, and write derived queries and paged queries. It also assumes basic JUnit 5 knowledge.
What @DataJpaTest starts
@DataJpaTest is a test slice annotation. It starts only the JPA layer of your application. It does not load controllers, services or the rest of your beans.
By default it does the following:
- It scans for
@Entityclasses and Spring Data repositories. - It replaces your configured
DataSourcewith an embedded database, such as H2, if one is on the classpath. - It wraps each test in a transaction and rolls it back when the test ends.
- It gives you a
TestEntityManagerand lets you inject your repositories.
The rollback keeps tests independent. Data saved in one test is gone before the next test starts.
A repository test
The test below saves an author with two books through cascade. It then checks a paged derived query.
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.data.domain.PageRequest;
import static org.assertj.core.api.Assertions.assertThat;
@DataJpaTest
class BookRepositoryTest {
@Autowired
private AuthorRepository authors;
@Autowired
private BookRepository books;
@Test
void findsBooksPublishedFromGivenYear() {
Author author = new Author("Ursula K. Le Guin");
author.addBook(new Book("A Wizard of Earthsea", 1968));
author.addBook(new Book("The Dispossessed", 1974));
authors.save(author);
var page = books.findByPublishedYearGreaterThanEqual(1970, PageRequest.of(0, 10));
assertThat(page.getContent()).extracting(Book::getTitle)
.containsExactly("The Dispossessed");
}
}The test assumes an AuthorRepository that extends JpaRepository<Author, Long>. Saving the author cascades to both books because the association uses CascadeType.ALL. The addBook helper sets both sides of the association, so each book gets its author value before the insert.
Common errors
The most common mistake is a test that passes without touching the database. The persistence context is a first-level cache, and the whole test runs in one transaction. A query method triggers a flush before it runs, so derived queries do see saved data. Reads by findById may come straight from the cache, though. That means a test can pass even when the SQL would fail.
To force a real round trip, inject TestEntityManager and call flush() and clear():
@Autowired
private TestEntityManager em;
@Test
void readsFromDatabaseNotCache() {
Author saved = authors.save(new Author("Ada"));
em.flush();
em.clear();
Author reloaded = authors.findById(saved.getId()).orElseThrow();
assertThat(reloaded.getName()).isEqualTo("Ada");
}flush() sends the pending SQL. clear() detaches all entities, so the next read must hit the database.
Other errors to watch for:
- Embedded database differs from production. H2 may accept SQL or types that your real database rejects. This matters most for native queries.
- Lazy loading in assertions. The test transaction stays open, so lazy access works in a test even when it would fail with a lazy loading error in production.
- Missing entity scan. If your entities are outside the package of your
@SpringBootApplicationclass, the slice does not find them.
Exercise
A test saves a Book with a repository, then calls findById in the same test and passes. Why might this not prove the insert SQL is valid, and how do you fix it?
Show answer
The entity is still in the persistence context, so findById can return the cached instance without any SQL. Inject TestEntityManager and call flush() to send the insert, then clear() to detach entities, so the next findById runs a real select.