【问题标题】:Spring-boot application-test.properties春季启动应用程序-test.properties
【发布时间】:2018-06-15 04:01:47
【问题描述】:

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

我的测试类是这样的

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

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

我的 ApplicationConfiguration 类看起来像这样

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

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

【问题讨论】:

  • 你能显示这个类ApplicationConfiguration
  • 我刚刚编辑了我的问题以添加 ApplicationConfiguration.. 当我运行应用程序时,它正在获取属性。问题仅在我运行测试用例时出现。
  • 属性对象是 null 还是 xxxxx 并且 yyyyy 是 null?
  • 您是否使用 spring-boot 初始化程序创建了这个项目?
  • @pvpkiran 属性对象不为空...只有字段为空

标签: spring-boot spring-boot-test application.properties


【解决方案1】:

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

@SpringBootTest(classes=ApplicationConfiguration.class)

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

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

这里的值被注入。但是要使用ConfigurationProperties 注入到一个类中,您需要使用@EnableConfigurationProperties 启用它

@EnableConfigurationProperties 放在您的测试类中,一切正常。

【讨论】:

  • 天啊!那行得通..非常感谢!除了这个,我什么都试过了!!
  • 谢谢你。困扰我很久了!
猜你喜欢
  • 1970-01-01
  • 2018-05-20
  • 1970-01-01
  • 2015-12-23
  • 2015-11-11
  • 2018-09-04
  • 2020-04-23
  • 1970-01-01
  • 2018-09-27
相关资源
最近更新 更多