Spring-boot application-test.properties

时间:2018-01-05 10:44:30

标签: 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;

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

我的ApplicationConfiguration类看起来像这样

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

我尝试了在谷歌上找到的所有可能方式..没有运气。请帮忙! 在此先感谢。

1 个答案:

答案 0 :(得分:14)

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

@SpringBootTest(classes=ApplicationConfiguration.class)

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

@Value("${xxxxx}")
private String xxxxx;

这里注入了值。但要注入ConfigurationProperties的课程,您需要使用@EnableConfigurationProperties

启用它

@EnableConfigurationProperties放在您的测试类上,并且每次操作都可以。