'Override a property for a single Spring Boot test

Consider the following example:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
    properties = {
        "some.property=valueA"
    })
public class ServiceTest {
    @Test
    public void testA() { ... }

    @Test
    public void testB() { ... }

    @Test
    public void testC() { ... }
}

I'm using SpringBootTest annotation's properties attribute to set some.property property's value for all tests in this test suite. Now I'd like to set another value of this property for one of this tests (let's say testC) without affecting the others. How can I achieve this? I've read the "Testing" chapter of Spring Boot docs, but I haven't found anything that'd match my use case.



Solution 1:[1]

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

Solution 2:[2]

Update

Possible with Spring 5.2.5 and Spring Boot 2.2.6

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

Solution 3:[3]

Just another solution in case you are using @ConfigurationProperties:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 timguy
Solution 3 Sam