I am using @TestPropertySource to overwrite application.yml properties in my integration test for a spring boot app.
@TestPropertySource(properties = { "repository.file.path=src/test/resources/x" })
I was wondering if there was some way to make the property VALUE dynamic. Something like this:
@TestPropertySource(properties = { "repository.file.path=PropertyValueProvider.class" })
Your feedback is appreciated. In my case the property value is system specific that should be generated upon the test run.
@DynamicPropertySource instead is used to: make it easier to set configuration properties from something else that's bootstrapped as part of running an integration test. This helps also setting up integration tests with Test Containers, getting rid of a lot of boilerplate code.
To change properties in a file during runtime, we should place that file somewhere outside the jar. Then we tell Spring where it is with the command-line parameter –spring. config. location=file://{path to file}.
@TestPropertySource
only provides declarative mechanisms for configuring PropertySource
s. Documentation in Spring Reference Manual.
If you need programmatic support for adding a PropertySource
to the Environment
, you should implement an ApplicationContextInitializer
which can be registered via @ContextConfiguration(initializers = ...)
. Documentation in Spring Reference Manual.
Regards,
Sam (author of the Spring TestContext Framework)
You can also do this with the @DynamicPropertySource
annotation in Spring Boot 5.2
See: https://github.com/spring-projects/spring-framework/issues/24540
Add this to your integration test class:
@DynamicPropertySource
static void dynamicProperties(DynamicPropertyRegistry registry) {
registry.add("my.property", () -> {
// some logic to get your property dynamically
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With