Spring-boot application-test.properties

Fun*_*ava 6 spring-boot spring-boot-test application.properties

我正在尝试使用junit对spring-boot应用程序进行单元测试.我已将application-test.properties放在src/test/resources下.我有一个ApplicationConfiguration类,它读取application.properties.

我的测试类看起来像这样

@RunWith(SpringRunner.class)
@SpringBootTest(classes=ApplicationConfiguration.class)
@TestPropertySource(locations = "classpath:application-test.properties")
@ActiveProfiles("test")
   public class TestBuilders {
      @Autowired
      private ApplicationConfiguration properties;
Run Code Online (Sandbox Code Playgroud)

当我尝试读取属性时,它始终为null.

我的ApplicationConfiguration类看起来像这样

@Configuration
@ConfigurationProperties
@PropertySources({
    @PropertySource("classpath:application.properties"),
    @PropertySource(value="file:config.properties", ignoreResourceNotFound = 
        true)})
public class ApplicationConfiguration{
    private xxxxx;
    private yyyyy;
Run Code Online (Sandbox Code Playgroud)

我尝试了所有可能的方法,我在谷歌上发现..没有运气.请帮忙!提前致谢.

pvp*_*ran 19

问题是你@EnableConfigurationProperties的测试课没有.
当你加载应用程序时,它从@SpringBootApplication你可能拥有的主类(有一个)@EnableConfigurationProperties开始,因此它在你启动应用程序时起作用.
而当您ApplicationConfiguration使用此处指定的类 运行测试时

@SpringBootTest(classes=ApplicationConfiguration.class)
Run Code Online (Sandbox Code Playgroud)

Spring不知道它必须启用配置属性,因此字段不会注入,因此为null.但春天正在读你的application-test.properties文件.这可以通过直接在测试类中注入值来确认

@Value("${xxxxx}")
private String xxxxx;
Run Code Online (Sandbox Code Playgroud)

这里注入了值.但要注入一个类,ConfigurationProperties你需要使用它来启用它@EnableConfigurationProperties

穿上@EnableConfigurationProperties你的考试班,每个人都可以正常工作.