0 day streak
java / beginner
Snippet

Verifying JPA Repository Queries with DataJpaTest

@DataJpaTest is a Spring Boot slice test annotation that focuses exclusively on JPA components. It configures an in-memory database, scans for @Entity classes, and configures Spring Data JPA repositories without starting the entire web server, making database integration tests fast and isolated.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@DataJpaTest
class UserRepositoryTest {
@Autowired
private UserRepository userRepository;
@Test
void shouldFindUserByEmail() {
User user = new User("[email protected]", "Alice");
userRepository.save(user);
Optional<User> found = userRepository.findByEmail("[email protected]");
assertTrue(found.isPresent());
assertEquals("Alice", found.get().getName());
}
}
spring
Breakdown
1
@DataJpaTest
Configures a focused test environment containing only Spring Data JPA repositories and an embedded database.
2
@Autowired private UserRepository userRepository;
Injects the repository bean under test directly into the test class.
3
userRepository.save(user);
Persists a test entity into the temporary in-memory database.
4
Optional<User> found = userRepository.findByEmail("[email protected]");
Executes the repository finder query to retrieve the persisted record.
5
assertTrue(found.isPresent());
Asserts that the query successfully located the user in the database.