java / beginner
Snippet
Testing Data Persistence with DataJpaTest
The @DataJpaTest annotation configures a focused JPA test environment with an embedded database to verify entity mapping and repository query behavior.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@DataJpaTestclass CustomerRepositoryTest {@Autowiredprivate TestEntityManager entityManager;@Autowiredprivate CustomerRepository repository;@Testvoid shouldFindCustomerByEmail() {entityManager.persistAndFlush(customer);Assertions.assertTrue(result.isPresent());}}
spring
Breakdown
1
@DataJpaTest
Bootstraps only JPA repositories and an in-memory database rather than the full application context.
2
entityManager.persistAndFlush(customer);
Persists the test entity and forces an immediate flush to the test database.
3
Assertions.assertTrue(result.isPresent());
Asserts that the repository query successfully found and returned the expected customer.