Spring JUnit5 测试未加载资源值

Spring JUnit5 test not loading resource values

我知道有很多关于此的问题,但他们都建议使用 @TestPropertySource@EnableConfigurationProperties。我已经用过了,但还是不行。

配置 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;
}

属性 来源 - src/test/resources/application-test.yml

api:
  enabled: true
  providers:
    - prov1
    - prov2

测试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}
}

测试配置 - src/test/.../MyTestConfiguration.java

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

当我 运行 测试,runTest() 并检查自动装配的 appConfig 值时,providers 为空,enabledfalse .这意味着未加载 yml 文件中的值。 我找到了 similar kind of question,但没有答案。

我认为你需要更换

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

@SpringBootTest(classes = {MyTestConfiguration.class})

然后application-test.yml会被自动拾取

我按照@sergey-tsypanov的建议修改了MyTest,然后删除了MyTestConfigurationclass。它有效并且 appConfig 具有价值。

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

    @Autowired
    private AppConfig appConfig;

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

看来即使我没有@SpringBootApplication,我也可以使用@SpringBootTest@EnableAutoConfiguration。我在 pom.xml

中有 spring 引导依赖