【发布时间】:2019-03-22 08:23:43
【问题描述】:
我的 Junit 没有拾取测试属性文件中设置的属性。 我没有收到错误,但从属性文件返回的值为 null
要测试的类:
package com.abc.mysource.mypackage;
@Component
@ComponentScan
public class MyHelper {
@Autowired
@Qualifier("commonProperties")
private CommonProperties commonProperties;
public LocalDateTime method1ThatUsesCommonProperties(LocalDateTime startDateTime) throws Exception {
String customUserType = commonProperties.getUserType(); // Returns null if run as JUnit test
//Further processing
}
}
支持组件 - bean 和配置类:
package com.abc.mysource.mypackage;
@Component
public class CommonProperties {
@Value("${myhelper.userType}")
private String userType;
public String getUserType() {
return userType;
}
public void setCalendarType(String userType) {
this.userType = userType;
}
}
配置类:
package com.abc.mysource.mypackage;
@Configuration
@ComponentScan(basePackages ="com.abc.mysource.mypackage.*")
@PropertySource("classpath:default.properties")
public class CommonConfig {}
src/main/resources 下的default.properties
myhelper.userType=PRIORITY
我的测试班:
package com.abc.mysource.mypackage.test;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes=MyHelper.class)
@TestPropertySource("classpath:default-test.properties")
@EnableConfigurationProperties
public class MyHelperTest {
@MockBean(name="commonProperties")
private CommonProperties commonProperties;
@Autowired
private MyHelper myHelper;
@Test
public void testMethod1ThatUsesCommonProperties() {
myHelper.method1ThatUsesCommonProperties();
}
}
default-test.properties 定义在 /src/test/resources 下:
myhelper.userType=COMMON
注意:
我将 default-test.properties 移至 /src/main/resources - commonProperties.getUserType() 为空
我什至使用了@TestPropertySource(properties = {"myhelper.userType=COMMON"})。结果一样
注意 2:
我在@TestPropertySource is not loading properties上尝试了解决方案。
此解决方案需要我在 src/test/java 下创建一个名为 CommonProperties 的重复 bean。但是当我这样做时@MockBean 失败了
@MockBean(name="commonProperties")
private CommonProperties commonProperties;
请不要标记重复。
注意 3: 我的是一个弹簧,而不是一个弹簧启动应用程序。
【问题讨论】:
-
你的问题对我有帮助,谢谢。
标签: java spring junit null properties-file