0 day streak
java / intermediate
Snippet

Testing Repository Queries with @DataJpaTest and DynamicPropertyRegistry

@DataJpaTest disables full component scanning and focuses purely on JPA repositories, reducing test execution overhead. Combining it with Testcontainers and @DynamicPropertySource allows integration testing against a real database instance rather than an in-memory substitute.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Testcontainers
class OrderRepositoryTests {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");
@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
@Autowired
private OrderRepository orderRepository;
@Test
void shouldFindOrdersByCustomerId() {
orderRepository.save(new OrderEntity("cust-101", new BigDecimal("49.99")));
List<OrderEntity> orders = orderRepository.findByCustomerId("cust-101");
assertThat(orders).hasSize(1);
}
}
spring
Breakdown
1
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
Prevents Spring Boot from replacing the configured DataSource with an embedded in-memory database like H2.
2
@DynamicPropertySource
Registers dynamic property values from the running container into the Spring Environment before tests run.
3
registry.add("spring.datasource.url", postgres::getJdbcUrl);
Supplies the dynamic JDBC URL of the active container to the Spring DataSource.