Override a property for a single Spring Boot test Override a property for a single Spring Boot test spring spring

Override a property for a single Spring Boot test


Your properties are evaluated by Spring during the Spring context loading.
So you cannot change them after the container has started.

As workaround, you could split the methods in multiple classes that so would create their own Spring context. But beware as it may be a bad idea as tests execution should be fast.

A better way could be having a setter in the class under test that injects the some.property value and using this method in the test to change programmatically the value.

private String someProperty;@Value("${some.property}")public void setSomeProperty(String someProperty) {    this.someProperty = someProperty;}


Update

Possible with Spring 5.2.5 and Spring Boot 2.2.6

@DynamicPropertySourcestatic void dynamicProperties(DynamicPropertyRegistry registry) {    registry.add("some.property", () -> "valueA");}


Just another solution in case you are using @ConfigurationProperties:

@Testvoid do_stuff(@Autowired MyProperties properties){  properties.setSomething(...);  ...}