java / intermediate
Snippet
Verifying Custom Query Logic via @DataJpaTest and TestEntityManager
The @DataJpaTest annotation disables full Spring context initialization and focuses strictly on JPA components. TestEntityManager provides an alternative to the standard EntityManager specifically configured for slice testing, ensuring test entities are persisted and flushed to an in-memory database before executing repository query assertions.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@DataJpaTestclass UserRepositoryTest {@Autowiredprivate TestEntityManager entityManager;@Autowiredprivate UserRepository userRepository;@Testvoid shouldFindActiveUsersByDepartment() {User user = new User("Alice", "Engineering", true);entityManager.persistAndFlush(user);List<User> result = userRepository.findByDepartmentAndActiveTrue("Engineering");assertThat(result).hasSize(1).contains(user);}}
spring
Breakdown
1
@DataJpaTest
Configures a focused test slice for JPA repositories and in-memory database configuration.
2
private TestEntityManager entityManager;
Injects a helper for setting up entity states and flushing database changes during tests.
3
entityManager.persistAndFlush(user);
Synchronizes the transient test entity directly into the underlying persistence context.