Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JUnit5 test not loading resource values

I know there are a lot of questions regarding this, but all of them are suggesting to use @TestPropertySource and @EnableConfigurationProperties. I have already used them but still not working.

Config class - src/main/java/com/demo/config/AppConfig.java

@Configuration
@ConfigurationProperties(prefix = "api")
@Getter
@Setter
public class AppConfig {
   private List<String> providers;
   private boolean enabled;
}

Property source - src/test/resources/application-test.yml

api:
  enabled: true
  providers:
    - prov1
    - prov2

Test class - src/test/../MyTest.java

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = MyTestConfiguration.class)
class MyTest {

    @Autowired
    private AppConfig appConfig;

    @Test
    void runTest() {//some code with breakpoint}
}

Test configuraton - src/test/.../MyTestConfiguration.java

@TestConfiguration
@TestPropertySource(locations = "classpath:application-test.yml")
@EnableConfigurationProperties(value = AppConfig.class)
@ActiveProfiles("test")
public class MyTestConfiguration {
}

When I run the test, runTest() and inspect autowired appConfig value, the providers are empty and enabled is false. That means the values in yml file were not loaded. I found a similar kind of question, but without answer.

like image 454
Ramanujan R Avatar asked Nov 14 '25 21:11

Ramanujan R


1 Answers

I think you need to replace

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = MyTestConfiguration.class)

with

@SpringBootTest(classes = {MyTestConfiguration.class})

Then application-test.yml will be picked up automatically.

like image 65
Sergey Tsypanov Avatar answered Nov 17 '25 11:11

Sergey Tsypanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!