'How to inject certain properties values during junit to a specific test
My Spring Boot app has some test that are reading their properties from the application.yml that is in the test folder.
cat:
maxAge:30
maxNameSize:10
all is working fine, but I like that in certain tests, other values will be injected:
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {
Cat.class
})
@SpringBootTest
public class CatTest {
@Test
public void testX(){
//inject maxAge=90
// use maxNameSize from the application.yml
....
@Test
public void testZ(){
//inject maxNameSize=5
// use maxAge from the application.yml
....
}
Solution 1:[1]
Changing properties on method level is not supported by Spring at this moment.
You can use nested classes to accomplish this.
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {
Cat.class
})
@SpringBootTest
public class CatTest {
@Nested
@SpringBootTest(properties = "cat.maxAge=90")
public class NestedTestX {
@Test
void testX() {
//noop
}
}
@Nested
@SpringBootTest(properties = "cat.maxNameSize=5")
public class NestedTestZ {
@Test
void testZ() {
//noop
}
}
}
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 | Pavel Polivka |
