0 day streak
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
@DataJpaTest
class CustomerRepositoryTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private CustomerRepository repository;
@Test
void shouldFindCustomerByEmail() {
Customer customer = new Customer("[email protected]");
entityManager.persistAndFlush(customer);
Optional<Customer> result = repository.findByEmail("[email protected]");
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.