春季启动应用程序test.properties [英] Spring-boot application-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;
当我尝试读取属性时,它始终为null.
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
.
加载应用程序时,它从可能有@EnableConfigurationProperties
的主类(具有@SpringBootApplication
的主类)开始,因此在启动应用程序时可以工作.
而当您仅在此处指定的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不知道它必须启用配置属性,因此这些字段没有注入,因此为null.但是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.
这篇关于春季启动应用程序test.properties的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!