@DataJpaTest for repositories
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A repository method such as findByName looks right but is checked only when it runs against a real database. How do you test ShopLite's queries without leaving test rows behind?
@DataJpaTest loads JPA, Flyway and repositories only
@DataJpaTest is a Spring Boot test annotation that starts only the data layer: the DataSource, Flyway, Hibernate and the Spring Data repositories. Each test runs in a transaction that is rolled back afterwards.
This test class loads only the data layer, so the test talks to the repository directly. A TestEntityManager is there to add rows.
@DataJpaTest@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)@ActiveProfiles("test")class CategoryRepositoryIT {
@Autowired private CategoryRepository categories;
@Autowired private TestEntityManager em;}Services, controllers and security are left out. Flyway runs the migrations when the context starts, so the test runs against the real schema, constraints included, and Hibernate's ddl-auto=validate checks that the entities match it.
The annotation also makes every test @Transactional: Spring starts a transaction before the test and rolls it back after, so rows a test adds never reach other tests. ShopLite's repository tests are named *IT because they need the MySQL test database, so Failsafe runs them in mvn verify.
Embedded database or real MySQL: @AutoConfigureTestDatabase
An embedded database is an in-memory database, such as H2, that starts inside the test JVM. @DataJpaTest swaps your DataSource for one by default, which is why a MySQL app must switch that off.
See what happens by default, then the two ways to use a real database. Example 1 shows the startup error; Example 2 starts MySQL in Docker.
Example 1 · The default: replace the DataSource with an embedded one
Runs in: a terminal in the shoplite-api project (Maven, MySQL test database)
@DataJpaTest // no @AutoConfigureTestDatabase: replace = NON_TEST (the default)class CategoryRepositoryIT { ...}[ERROR] com.shoplite.category.CategoryRepositoryIT.findByNameIgnoresCase -- Time elapsed: 0.008 s <<< ERROR! java.lang.IllegalStateException: Failed to load ApplicationContext for [MergedContextConfiguration@4f9a2c08 testClass = com.shoplite.category.CategoryRepositoryIT, ...] ... Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': ... Caused by: java.lang.IllegalStateException: Failed to replace DataSource with an embedded database for tests. If you want an embedded database please put a supported one on the classpath or tune the replace attribute of @AutoConfigureTestDatabase.
What this code does
- With no
@AutoConfigureTestDatabase, the slice tries to replace ShopLite's MySQLDataSourcewith an in-memory database. - ShopLite has no H2, HSQLDB or Derby dependency, so the context cannot start. The message tells you both ways out.
- ShopLite picks
replace = NONEplus@ActiveProfiles("test"): real MySQL, real collation, real Flyway scripts.
Example 2 · Option: a MySQL container with Testcontainers
Runs in: a Spring Boot 4.1 project with Docker running
// pom.xml (test scope): spring-boot-testcontainers, testcontainers-junit-jupiter, testcontainers-mysqlpackage com.shoplite.category;
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;import org.springframework.boot.testcontainers.service.connection.ServiceConnection;import org.testcontainers.junit.jupiter.Container;import org.testcontainers.junit.jupiter.Testcontainers;import org.testcontainers.mysql.MySQLContainer;
/** The same repository tests on a throw-away MySQL 8.4 in Docker: no local test database needed. */@DataJpaTest@Testcontainersclass CategoryRepositoryContainerIT {
@Container @ServiceConnection // Boot points the DataSource at this container static MySQLContainer mysql = new MySQLContainer("mysql:8.4");
// ... the same @Autowired fields and @Test methods as CategoryRepositoryIT}INFO tc.mysql:8.4 : Creating container for image: mysql:8.4 INFO tc.mysql:8.4 : Container mysql:8.4 is starting: 9c41d0e5b7a2... INFO tc.mysql:8.4 : Container mysql:8.4 started in PT14.218S INFO o.f.core.internal.command.DbMigrate : Successfully applied 5 migrations to schema `test`, now at version v5 [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 21.37 s -- in com.shoplite.category.CategoryRepositoryContainerIT
What this code does
@Containerstarts the container once for the class;@ServiceConnectiongives Boot its JDBC URL, user and password, so noapplication-test.propertiesis needed.- The default
replace = NON_TESTkeeps aDataSourcethat comes from a service connection, so no@AutoConfigureTestDatabaseis needed either. - The first start pulls the image and takes time; it needs Docker running. Section 20 (Testcontainers integration tests) covers containers in depth. ShopLite's course setup uses the local MySQL test database instead.
ShopLite has no H2, HSQLDB or Derby on its classpath, so the default fails at startup. Even with H2, MySQL-specific behaviour would differ: the case-insensitive collation behind findByName, FOR UPDATE locks, MySQL syntax in the Flyway scripts. @AutoConfigureTestDatabase(replace = Replace.NONE) keeps the configured DataSource, which with @ActiveProfiles("test") is the MySQL test database from application-test.properties.
Testcontainers is the other real-database option: the test starts a throw-away MySQL in Docker and Boot's @ServiceConnection points the DataSource at it. It needs Docker instead of a local MySQL. Boot 4.1 manages Testcontainers 2.x, where the class is org.testcontainers.mysql.MySQLContainer (1.x used org.testcontainers.containers).
Fix the error
Keep the MySQL DataSource
The context fails to start. Pick the line that keeps ShopLite on MySQL.
Which replacement for line 2 fixes the error?
Error
Failed to replace DataSource with an embedded database for tests. If you want an embedded database please put a supported one on the classpath.
TestEntityManager to arrange rows; rollback after each test
TestEntityManager is a small test helper around JPA's EntityManager with persist, persistAndFlush, find, flush and clear. You use it to arrange rows, so only the method under test goes through the repository.
Arrange rows with TestEntityManager, call only the repository method under test, and let the rollback clean up. Example 3 is the test; Example 4 shows why the rollback matters.
Example 3 · src/test/java/com/shoplite/category/CategoryRepositoryIT.java
Runs in: a terminal in the shoplite-api project (Maven, MySQL test database)
package com.shoplite.category;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase;import org.springframework.boot.jpa.test.autoconfigure.TestEntityManager;import org.springframework.test.context.ActiveProfiles;
import com.shoplite.product.Product;
/** * CategoryRepository on the MySQL test database. Every test adds its own rows with names * no seed row uses, and the test transaction is rolled back afterwards. */@DataJpaTest@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) // MySQL, not an embedded database@ActiveProfiles("test")class CategoryRepositoryIT {
@Autowired private CategoryRepository categories;
@Autowired private TestEntityManager em;
@Test void findByNameIgnoresCase() { em.persistAndFlush(new Category("Smart Watches", null));
assertThat(categories.findByName("smart WATCHES")).get() .extracting(Category::getName).isEqualTo("Smart Watches"); assertThat(categories.findByName("Smart Watch")).isEmpty(); }
@Test void existsByParentIdSeesSubCategories() { Category wearables = em.persist(new Category("Wearables Test", null)); em.persist(new Category("Fitness Bands Test", wearables)); Category giftCards = em.persist(new Category("Gift Cards Test", null)); em.flush();
assertThat(categories.existsByParentId(wearables.getId())).isTrue(); assertThat(categories.existsByParentId(giftCards.getId())).isFalse(); }
@Test void hasProductsLooksAtProductsOfThatCategory() { Category stationery = em.persist(new Category("Stationery Test", null)); Category empty = em.persist(new Category("Empty Shelf Test", null)); em.persist(new Product("STN-PEN01", "Gel Pen Pack of 10", stationery, new BigDecimal("120.00"), 50)); em.flush();
assertThat(categories.hasProducts(stationery.getId())).isTrue(); assertThat(categories.hasProducts(empty.getId())).isFalse(); }}$ ./mvnw verify -Dit.test=CategoryRepositoryIT -Dtest=none -Dsurefire.failIfNoSpecifiedTests=false ... Hibernate: insert into categories (name,parent_id) values (?,?) Hibernate: select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.name=? ... [INFO] Running com.shoplite.category.CategoryRepositoryIT [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 5.912 s -- in com.shoplite.category.CategoryRepositoryIT [INFO] [INFO] Results: [INFO] [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] BUILD SUCCESS
What this code does
findByName("smart WATCHES")finds "Smart Watches" because the MySQL column's collation ignores case. On H2 this test would fail: one reason ShopLite tests on MySQL.- Each test arranges its own rows with
TestEntityManagerand flushes them, then calls only the repository method under test. @DataJpaTestshows the SQL by default (showSql = true), handy for checking what a derived query really runs.
Example 4 · Why the rollback keeps tests independent
import java.util.ArrayList;import java.util.List;
/** A table with a unique name column and simple transactions: begin takes a copy, rollback restores it. */class CategoryTable { private List<String> names = new ArrayList<>(List.of("Electronics", "Mobiles")); private List<String> snapshot;
void begin() { snapshot = new ArrayList<>(names); }
void rollback() { names = snapshot; }
void insert(String name) { for (String existing : names) { if (existing.equalsIgnoreCase(name)) { throw new IllegalStateException("Duplicate entry '" + name + "' for key 'uq_categories_name'"); } } names.add(name); }
int count() { return names.size(); }}
public class RollbackDemo { static void test(String testName, CategoryTable table, boolean rollbackAfter) { table.begin(); try { table.insert("Smart Watches"); System.out.println(" PASS " + testName + " (rows now " + table.count() + ")"); } catch (IllegalStateException e) { System.out.println(" FAIL " + testName + ": " + e.getMessage()); } finally { if (rollbackAfter) { table.rollback(); } } }
public static void main(String[] args) { System.out.println("Without rollback (each test commits):"); CategoryTable committed = new CategoryTable(); test("savesSmartWatches", committed, false); test("findsSmartWatchesByName", committed, false); System.out.println(" rows left behind: " + committed.count());
System.out.println("With rollback after each test (what @DataJpaTest does):"); CategoryTable rolledBack = new CategoryTable(); test("savesSmartWatches", rolledBack, true); test("findsSmartWatchesByName", rolledBack, true); System.out.println(" rows left behind: " + rolledBack.count()); }}Without rollback (each test commits): PASS savesSmartWatches (rows now 3) FAIL findsSmartWatchesByName: Duplicate entry 'Smart Watches' for key 'uq_categories_name' rows left behind: 3 With rollback after each test (what @DataJpaTest does): PASS savesSmartWatches (rows now 3) PASS findsSmartWatchesByName (rows now 3) rows left behind: 2
What this code does
- The table has a unique name rule, like
uq_categories_name. Two tests both insert "Smart Watches". - When each test commits, the second one fails because of the first: the tests depend on their order.
- Rolling back after each test (what
@DataJpaTestdoes) gives every test the same starting rows, and leaves nothing behind.
flush() sends the pending INSERTs to MySQL inside the open transaction, so the query then sees them. At the end, the rollback removes them again, without any cleanup code.
The test database may already hold seed rows from other *IT classes. Give your rows names no seed row uses ("Smart Watches", "Gadgets Test") and assert only on them, so the test passes whatever else is in the tables.
Order of execution
Life of a repository test
Put the steps of one repository test in the order they happen.
Testing derived queries, @Query methods and pagination
A persistence context is Hibernate's cache of the entities loaded or saved inside one transaction. Asking for the same row again returns the cached object, not a fresh read from MySQL.
Test each query with a row that matches and one that does not. Example 5 covers a search, paging and a @Modifying update; Example 6 shows what a page holds.
Example 5 · src/test/java/com/shoplite/product/ProductRepositoryIT.java
Runs in: a terminal in the shoplite-api project (Maven, MySQL test database)
package com.shoplite.product;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;
import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase;import org.springframework.boot.jpa.test.autoconfigure.TestEntityManager;import org.springframework.data.domain.Page;import org.springframework.data.domain.PageRequest;import org.springframework.data.domain.Sort;import org.springframework.test.context.ActiveProfiles;
import com.shoplite.category.Category;
/** Derived query, @Query search with paging, and the @Modifying stock update, on MySQL. */@DataJpaTest@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)@ActiveProfiles("test")class ProductRepositoryIT {
@Autowired private ProductRepository products;
@Autowired private TestEntityManager em;
private Category gadgets;
@BeforeEach void addThreeGadgets() { // runs inside each test's transaction, so it is rolled back too gadgets = em.persist(new Category("Gadgets Test", null)); em.persist(new Product("GDT-FAN01", "USB Desk Fan", gadgets, new BigDecimal("499.00"), 10)); em.persist(new Product("GDT-LMP01", "LED Study Lamp", gadgets, new BigDecimal("899.00"), 0)); em.persist(new Product("GDT-SPK01", "Bluetooth Speaker", gadgets, new BigDecimal("1499.00"), 25)); em.flush(); }
@Test void findBySkuFindsOneProduct() { assertThat(products.findBySku("GDT-LMP01")).get() .extracting(Product::getName).isEqualTo("LED Study Lamp"); assertThat(products.findBySku("GDT-NONE")).isEmpty(); }
@Test void searchPagesByCategoryMostExpensiveFirst() { Page<Product> page = products.search(null, gadgets.getId(), null, null, false, false, PageRequest.of(0, 2, Sort.by(Sort.Direction.DESC, "price")));
assertThat(page.getContent()).extracting(Product::getSku).containsExactly("GDT-SPK01", "GDT-LMP01"); assertThat(page.getTotalElements()).isEqualTo(3); assertThat(page.getTotalPages()).isEqualTo(2); }
@Test void searchFiltersByTextAndStock() { Page<Product> lamps = products.search("%lamp%", gadgets.getId(), null, null, false, false, PageRequest.of(0, 20)); Page<Product> inStock = products.search(null, gadgets.getId(), null, null, true, false, PageRequest.of(0, 20, Sort.by("id")));
assertThat(lamps.getContent()).extracting(Product::getSku).containsExactly("GDT-LMP01"); assertThat(inStock.getContent()).extracting(Product::getSku).containsExactly("GDT-FAN01", "GDT-SPK01"); }
@Test void takeStockChangesTheRowOnlyWhenThereIsEnough() { Product fan = products.findBySku("GDT-FAN01").orElseThrow();
assertThat(products.takeStock(fan.getId(), 4)).isEqualTo(1); assertThat(products.takeStock(fan.getId(), 7)).isZero(); // only 6 left
em.clear(); // the UPDATE went straight to MySQL; drop the cached Product with stock 10 assertThat(em.find(Product.class, fan.getId()).getStock()).isEqualTo(6); }}Hibernate: select p1_0.product_id,p1_0.category_id,c1_0.category_id,c1_0.name,c1_0.parent_id,p1_0.is_active,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 join categories c1_0 on c1_0.category_id=p1_0.category_id where (? is null or lower(p1_0.name) like ? escape '!' or lower(p1_0.sku) like ? escape '!') and (? is null or c1_0.category_id=?) and ... order by p1_0.price desc limit ?,? Hibernate: select count(p1_0.product_id) from products p1_0 where ... Hibernate: update products p1_0 set stock=(p1_0.stock-?) where p1_0.product_id=? and p1_0.stock>=? ... [INFO] Running com.shoplite.product.ProductRepositoryIT [INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.204 s -- in com.shoplite.product.ProductRepositoryIT
What this code does
@BeforeEachruns inside each test's transaction, so the three gadgets are rolled back after every test too.- The paging test checks the rows in order and both totals; the second search test covers the text and the in-stock filters of the same
@Query. takeStockreturns 1, then 0 when only 6 are left. Withoutem.clear(),em.findwould return the cached fan with stock 10.
Example 6 · What a page should contain: rows and totals
import java.math.BigDecimal;import java.util.Comparator;import java.util.List;
record Product(int id, String sku, BigDecimal price) {}
/** What a Spring Data Page tells you: the rows of one page and the totals of the whole result. */record Page(List<String> content, int page, int size, int totalElements, int totalPages) {}
public class PageDemo { static Page page(List<Product> all, Comparator<Product> order, int page, int size) { List<Product> sorted = all.stream().sorted(order).toList(); int from = Math.min(page * size, sorted.size()); int to = Math.min(from + size, sorted.size()); List<String> content = sorted.subList(from, to).stream().map(Product::sku).toList(); int totalPages = (sorted.size() + size - 1) / size; return new Page(content, page, size, sorted.size(), totalPages); }
public static void main(String[] args) { List<Product> gadgets = List.of( new Product(21, "GDT-FAN01", new BigDecimal("499.00")), new Product(22, "GDT-LMP01", new BigDecimal("899.00")), new Product(23, "GDT-SPK01", new BigDecimal("1499.00"))); // sort=price,desc; ties broken by id ascending, as the contract asks Comparator<Product> byPriceDesc = Comparator.comparing(Product::price).reversed() .thenComparing(Product::id);
for (int p = 0; p <= 2; p++) { System.out.println(page(gadgets, byPriceDesc, p, 2)); } }}Page[content=[GDT-SPK01, GDT-LMP01], page=0, size=2, totalElements=3, totalPages=2] Page[content=[GDT-FAN01], page=1, size=2, totalElements=3, totalPages=2] Page[content=[], page=2, size=2, totalElements=3, totalPages=2]
What this code does
- Sort by price descending, ties by id, then cut the list into pages of 2: page 0 has the speaker and the lamp, page 1 the fan.
totalPagesis the element count divided by the size, rounded up: 3 elements, size 2 → 2 pages.- A page past the end is empty but keeps the real totals, which is what the contract and Spring Data's
Pagegive.
A derived query such as findBySku gets its SQL from the method name; an @Query method carries its own JPQL. Both are only checked when they run. For a paged method, pass a PageRequest.of(page, size, sort) and check the rows in order, getTotalElements() and getTotalPages(); a wrong count query is a bug that only the totals reveal.
A @Modifying query (takeStock) changes rows in MySQL directly and skips the persistence context. A product loaded earlier still shows the old stock until you call em.clear().
Find the bug
Find the weak check
Click the line that makes the test pass when it should not, or fail when it should not.
The fan has stock 10; takeStock removes 4. The test fails with 10. Which line is wrong?
Next step
Check your understanding
11 quick questions