我的 Junit 没有获取测试属性文件中设置的属性。 我没有收到错误,但从属性文件返回的值为空
要测试的类别:
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() 为 null
我什至使用了@TestPropertySource(properties = {"myhelper.userType=COMMON"})。结果相同
注2:
我尝试了 @TestPropertySource is not loading properties 上的解决方案.
此解决方案要求我在 src/test/java 下创建一个名为 CommonProperties 的重复 bean。但是当我这样做时 @MockBean 失败了
@MockBean(name="commonProperties")
private CommonProperties commonProperties;
请不要标记重复项。
注3: 我的是一个spring,而不是一个spring boot应用程序。
最佳答案
如果您不需要特定状态,MockBeans 就适合。通常这个bean是“隔离的”,并且这个bean的每个方法调用都会有相同的结果。它是“隔离的”->使用@Value注释的服务将不适用于此bean。
您需要的是一个正确构造和初始化的“正常”bean。请使用 @Autowired 注释并根据需要使用测试配置文件定义另一个 bean。
关于java - @TestPropertySource - 测试属性文件中的值未设置/设置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52858552/