पाठ 15 / 25

Repository Tests With @DataJpaTest

Queries against a real (embedded) database.

Test queries, not frameworks

@DataJpaTest starts only JPA components with an embedded database, and each test runs in a transaction that is rolled back afterwards. Use it to verify your queries (derived queries, @Query, mappings), not Spring Data itself. For production-like behaviour, run the same tests against the real database engine with Testcontainers, because H2 differs from PostgreSQL or MySQL in SQL details.

A repository test

This file is from a demo "shop" service generated by start.spring.io for Spring Boot 4.1.1 and Java 21 (Temurin 21.0.12), built with Maven 3.9.16; the project compiled and its tests passed. The derived query is checked for both filtering and sorting.

package com.example.shop;

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;

@DataJpaTest                                        // JPA layer with an in-memory database
class ProductRepositoryTest {

    @Autowired ProductRepository repo;

    @Test
    void derivedQueryFiltersAndSorts() {
        repo.save(new Product("Lamp", new BigDecimal("1499")));
        repo.save(new Product("Pen", new BigDecimal("899")));
        repo.save(new Product("Notebook", new BigDecimal("120")));
        assertThat(repo.findByPriceLessThanOrderByPriceAsc(new BigDecimal("1000")))
            .extracting(Product::getName)
            .containsExactly("Notebook", "Pen");
    }
}

Use Testcontainers for real engines

Spring Boot has built-in Testcontainers support (@ServiceConnection) to run tests against the same database version as production.

त्वरित जाँच: What happens to data written in a @DataJpaTest test by default?

  • It is rolled back after each test
  • It is committed permanently
  • It is written to production
  • It is exported to CSV
Answer

It is rolled back after each test — Tests stay isolated.