Spring-boot 应用程序-test.properties [英] Spring-boot application-test.properties

查看:46
本文介绍了Spring-boot 应用程序-test.properties的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to unit test the spring-boot application using junit. I have placed the application-test.properties under src/test/resources. I have a ApplicationConfiguration Class which reads the application.properties.

我的测试类是这样的

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

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

When I try to read the properties, it is always null.

我的 ApplicationConfiguration 类看起来像这样

My ApplicationConfiguration Class looks something like this

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

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

I tried all possible ways that I found on google.. No luck. Please help! Thanks in Advance.

推荐答案

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

The issue is you don't have @EnableConfigurationProperties on your test class.
When you load the application it start from main class(one which has @SpringBootApplication) where you might have @EnableConfigurationProperties and hence it works when you start the application.
Whereas when you are running the Test with only ApplicationConfiguration class as you have specified here

@SpringBootTest(classes=ApplicationConfiguration.class)

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

Spring doesn't know that it has to Enable Configuration Properties and hence the fields are not injecting and hence null. But spring is reading your application-test.properties file. This can be confirmed by just injecting the value directly in your test class

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

这里注入了值.但是要注入具有 ConfigurationProperties 的类,您需要使用 @EnableConfigurationProperties

Here the value is injected. But to inject into a class with ConfigurationProperties you need to enable it using @EnableConfigurationProperties

@EnableConfigurationProperties 放在您的测试类上,一切正常.

Put @EnableConfigurationProperties on your test class and everythhing works fine.

这篇关于Spring-boot 应用程序-test.properties的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆