Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 895
korolar Avatar asked Feb 01 '18 19:02

korolar


People also ask

Where does spring boot look for property file in test?

properties file in the classpath (src/main/resources/application. properties).

How do I read test properties in spring boot?

You can use @TestPropertySource annotation in your test class. Just annotate @TestPropertySource("classpath:config/mailing. properties") on your test class. You should be able to read out the property for example with the @Value annotation.


3 Answers

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;
}
like image 136
davidxxx Avatar answered Oct 20 '22 07:10

davidxxx


Update

Possible at least with Spring 5.2.5 and Spring Boot 2.2.6

@DynamicPropertySource
static void dynamicProperties(DynamicPropertyRegistry registry) {
    registry.add("some.property", () -> "valueA");
}
like image 44
timguy Avatar answered Oct 20 '22 08:10

timguy


Just another solution in case you are using @ConfigurationProperties:

@Test
void do_stuff(@Autowired MyProperties properties){
  properties.setSomething(...);
  ...
}
like image 2
Sam Avatar answered Oct 20 '22 07:10

Sam