我的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();
}
}
支持组件-bean和config类:
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();
}
}
在/src/test/resources下定义的default-test.properties:
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下创建一个称为通用属性的重复bean。但是@mockbean失败了
@MockBean(name="commonProperties")
private CommonProperties commonProperties;
请不要标记副本。
注3:
我的是弹簧,不是弹簧引导应用程序。