Reputation: 1535
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.
Upvotes: 47
Views: 41209
Reputation: 328614
With JUnit 5, you should be able to reduce the necessary code by using nested tests. Add the default config to the outer test class and the override annotations to the nested tests.
See also:
Upvotes: 2
Reputation: 593
I hit the same problem with one of my integration tests, but I prefer to use @ConfigurationProperties
in my code and that was key here.
After getting nowhere trying to set properties through various other methods, I realised I could just autowire my properties class and simply set the value I wanted in each specific test.
NB: If this were a unit test, I would have been able to mock my properties class just as easily.
Upvotes: 1
Reputation: 2582
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");
}
Upvotes: 13
Reputation: 2049
Just another solution in case you are using @ConfigurationProperties
:
@Test
void do_stuff(@Autowired MyProperties properties){
properties.setSomething(...);
...
}
Upvotes: 4
Reputation: 131346
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;
}
Upvotes: 25