Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@TestPropertySource with dynamic properties

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.

like image 490
Vladimir Avatar asked Nov 22 '15 14:11

Vladimir


People also ask

What is @DynamicPropertySource?

@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.

How do you change application properties at runtime spring boot?

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}.


2 Answers

@TestPropertySource only provides declarative mechanisms for configuring PropertySources. 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)

like image 181
Sam Brannen Avatar answered Oct 05 '22 14:10

Sam Brannen


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
   });
}
like image 34
Amrit Baveja Avatar answered Oct 05 '22 13:10

Amrit Baveja