Home > database >  Spring JUnit5 test not loading resource values
Spring JUnit5 test not loading resource values

Time:02-10

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.

CodePudding user response:

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.

CodePudding user response:

I modified MyTest as @sergey-tsypanov suggested and then deleted MyTestConfiguration class. It worked and appConfig has values.

@SpringBootTest(classes = AppConfig.class)
@EnableAutoConfiguration
@ActiveProfiles("test")
class MyTest {

    @Autowired
    private AppConfig appConfig;

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

It seems even if I don't have @SpringBootApplication, I can use @SpringBootTest and @EnableAutoConfiguration. I had spring Boot dependency in pom.xml

  • Related