java / beginner
Snippet
Verifying Database Queries with DataJpaTest Slice
The @DataJpaTest annotation configures an in-memory database and scans only @Entity and Spring Data JPA repository beans. This provides fast, focused integration testing for the data persistence layer without loading the entire application context.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@DataJpaTestclass UserRepositoryTest {@Autowiredprivate UserRepository userRepository;@Testvoid shouldFindUserByEmail() {userRepository.save(user);assertTrue(found.isPresent());}}
spring
Breakdown
1
@DataJpaTest
Applies JPA test slicing, automatically setting up an embedded database and configuring transaction rollback after each test.
2
private UserRepository userRepository;
Injects the Spring Data JPA repository instance under test.
3
Optional<User> found = userRepository.findByEmail("[email protected]");
Executes the repository finder query to retrieve the persisted entity by its email attribute.
4
assertTrue(found.isPresent());
Asserts that the query returned a non-empty Optional containing the user.