import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import static org.assertj.core.api.Assertions.assertThat; @DataJpaTest class UserRepositoryTest { @Autowired private UserRepository userRepository; @Test void testSaveAndFind() { User user = new User(null, "Alice"); userRepository.save(user); User found = userRepository.findByName("Alice"); assertThat(found).isNotNull(); assertThat(found.getName()).isEqualTo("Alice"); } }
@DataJpaTest sets up an in-memory database and scans for JPA repositories. It injects the repository bean, so userRepository is available. The test saves a user and finds it by name, so assertions pass.
import static org.junit.jupiter.api.Assertions.*;
List<User> users = userRepository.findAll();findAll() returns an empty list if no users exist. Using assertTrue(users.isEmpty()) directly checks that the list has no elements.
@DataJpaTest class UserRepositoryTest { @Autowired private UserRepository userRepository; @Test void testFind() { User user = userRepository.findByName("Bob"); assertNull(user); } }
@DataJpaTest scans for JPA repositories only in the package of the test class and its subpackages. If UserRepository is outside this scope, it won't be found, causing NoSuchBeanDefinitionException.
@DataJpaTest auto-configures an embedded in-memory H2 database by default if no other datasource is configured. It does not use production databases or mocks repositories.
@DataJpaTest runs each test method in a transaction that rolls back by default after the test finishes. Adding @Transactional with NOT_SUPPORTED disables transactions, and @Commit or @Rollback(false) change rollback behavior.