@DataJpaTest helps you test your database repositories easily without starting the whole application. It sets up only what is needed for database tests.
@DataJpaTest for repository testing in Spring Boot
@DataJpaTest
public class YourRepositoryTest {
@Autowired
private YourRepository repository;
@Test
public void testMethod() {
// test code here
}
}@DataJpaTest loads only JPA-related components like repositories and configures an in-memory database by default.
You usually use @Autowired to inject the repository you want to test.
findByUsername in the UserRepository.@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()); } }
@DataJpaTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) public class ProductRepositoryTest { @Autowired private ProductRepository productRepository; @Test public void testSaveProduct() { Product product = new Product("Book", 9.99); productRepository.save(product); assertTrue(productRepository.findById(product.getId()).isPresent()); } }
This test saves a book entity and then finds it by title using the repository method. It checks that the saved book is found correctly.
package com.example.demo; 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(); book.setTitle("Spring Boot Guide"); bookRepository.save(book); Book found = bookRepository.findByTitle("Spring Boot Guide"); assertNotNull(found); assertEquals("Spring Boot Guide", found.getTitle()); } }
@DataJpaTest uses an in-memory database by default, so your tests run fast and isolated.
If you want to use your real database, add @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE).
Remember to keep tests small and focused on repository logic only.
@DataJpaTest is for testing JPA repositories without starting the full app.
It sets up an in-memory database and repository beans automatically.
Use it to write fast, focused tests for your database access code.