@DataJpaTest helps test database repositories easily by setting up only what is needed for database access. It makes tests faster and simpler.
0
0
@DataJpaTest for repository testing in JUnit
Introduction
When you want to check if your database queries return correct data.
When you want to test saving, updating, or deleting data in your repository.
When you want to test repository methods without starting the whole application.
When you want to verify that your entity mappings and database schema work well.
When you want to run fast tests focused only on data access logic.
Syntax
JUnit
@DataJpaTest
public class YourRepositoryTest {
@Autowired
private YourRepository repository;
@Test
public void testMethod() {
// test code here
}
}@DataJpaTest automatically configures an in-memory database by default.
You usually use @Autowired to inject the repository you want to test.
Examples
This example tests finding a user by username after saving it.
JUnit
@DataJpaTest public class UserRepositoryTest { @Autowired private UserRepository userRepository; @Test public void testFindByUsername() { User user = new User("john", "John Doe"); userRepository.save(user); User found = userRepository.findByUsername("john"); assertEquals("John Doe", found.getFullName()); } }
This example shows how to use your real database instead of in-memory by disabling replacement.
JUnit
@DataJpaTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) public class ProductRepositoryTest { @Autowired private ProductRepository productRepository; @Test public void testCount() { long count = productRepository.count(); assertTrue(count >= 0); } }
Sample Program
This test saves a book and then finds it by ISBN to check if saving and finding works correctly.
JUnit
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; @DataJpaTest public class BookRepositoryTest { @Autowired private BookRepository bookRepository; @Test public void testSaveAndFind() { Book book = new Book("123", "Test Driven Development"); bookRepository.save(book); Book found = bookRepository.findByIsbn("123"); assertNotNull(found); assertEquals("Test Driven Development", found.getTitle()); } }
OutputSuccess
Important Notes
@DataJpaTest rolls back transactions after each test to keep tests isolated.
It uses an in-memory database like H2 by default, so no real database setup is needed.
You can add @AutoConfigureTestDatabase to customize database behavior.
Summary
@DataJpaTest is for testing Spring Data JPA repositories easily and quickly.
It sets up only database-related parts and uses an in-memory database by default.
Tests run faster and are isolated because transactions roll back after each test.