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.
properties file in the classpath (src/main/resources/application. properties).
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.
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 at least with Spring 5.2.5 and Spring Boot 2.2.6
@DynamicPropertySource
static void dynamicProperties(DynamicPropertyRegistry registry) {
registry.add("some.property", () -> "valueA");
}
Just another solution in case you are using @ConfigurationProperties
:
@Test
void do_stuff(@Autowired MyProperties properties){
properties.setSomething(...);
...
}
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