java - 在 JUnit 测试中使用来自 src/main/resources 的实际属性文件和 Spring @PropertySource
问题描述
我正在尝试通过使用 H2 数据库而不是实际数据库来对 DAO 类进行单元测试。我在尝试让我的测试用例使用文件src/main/resources/properties/
夹中存在的属性文件时遇到问题:
测试班
@RunWith(SpringJUnit4ClassRunner.class)
@PropertySource("classpath:properties/common.properties")
@ContextConfiguration(locations = { "/spring/common-context.xml" })
public class ConfigDAOImplTest {
@Autowired
private ConfigDAOImpl configDAO;
@Spy
private ContextParamDAO contextParamDAO = new ContextParamDAOImpl();
private static final String SCHEMA_CONFIG = "classpath:data/CONFIG_SCHEMA.sql";
private static final String DATA_CONFIG = "classpath:data/CONFIG_DATA.sql";
@Before
public void init() {
MockitoAnnotations.initMocks(this);
DataSource dataSource = new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript(SCHEMA_CONFIG)
.addScript(DATA_CONFIG)
.build();
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
//override the jdbcTemplate for the test case
configDAO.setJdbcTemplate(jdbcTemplate);
configDAO.setContextParamDAO(contextParamDAO);
}
//.. more coode
}
通用上下文.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="commonAppProperties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreResourceNotFound" value="true" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="locations">
<list>
<value>file:${conf_folder_path}/common.properties</value>
</list>
</property>
</bean>
<bean id="configDAO"
class="com.myproject.common.dataaccess.impl.ConfigDAOImpl" scope="step">
<property name="jdbcTemplate" ref="jdbcTemplate" />
<property name="corePoolSize" value="${threadpool.size}"/>
</bean>
</beans>
当我运行测试类时,出现以下异常:
Caused by: org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'corePoolSize'; nested exception is java.lang.NumberFormatException: For input string: "${threadpool.size}"
测试用例无法找到所需属性的原因之一是:
PropertyPlaceholderConfigurer
bean 指的 是Maven 构建系统复制到{conf_folder_path}/common.properties
的路径 。src/main/resources/properties/common.properties
- 但是,在 Eclipse 中,没有
{conf_folder_path}
,因为它是由 Maven 创建的。
问题:假设上述原因是问题的根本原因,考虑到Spring上下文中引用的路径与源代码中的路径不同,如何让测试用例找到属性。
解决方案
您可以创建如下内容:
@Configuration
public class TestConfiguration {
private static final Logger log = LoggerFactory.getLogger(TestConfiguration.class);
@Autowired
private Environment env;
/**
* This bean is necessary in order to use property file from src/main/resources/properties
* @param env environment
* @return property source configurator with correct property file
*/
@Bean
public PropertySourcesPlaceholderConfigurer placeholderConfigurerDev(ConfigurableEnvironment env) {
final String fileName = "common.properties";
Path resourceDirectory = Paths.get("src","main","resources", "properties");
String absolutePath = resourceDirectory.toFile().getAbsolutePath();
final File file = new File(absolutePath.concat("/").concat(fileName));
if (file.exists()) {
try {
MutablePropertySources sources = env.getPropertySources();
sources.addFirst(new PropertiesPropertySource(fileName, PropertiesLoaderUtils.loadAllProperties(file.getName())));
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
throw new RuntimeException(ex.getMessage(), ex);
}
}
this.env = env;
return new PropertySourcesPlaceholderConfigurer();
}
推荐阅读
- c++ - 有没有办法创建一个中央程序来处理我电脑的不同 RGB 组件?
- java - Apache Ignite 持久性问题/警告
- firebase-cloud-messaging - 订阅者离线时的 FCM 推送通知
- python - Python 数据类:从 asdict 中省略字段
- javascript - 如何仅使用 JavaScript 为两个以上的输入字段准确显示表单验证错误消息?
- python - Django Model.objects.all() 查询集不明显
- neo4j - 在neo4j中合并两个子图
- flutter - Flutter 如何在 build() 中重新创建有状态的小部件
- reactjs - React Icons - pull icon dynamically
- javascript - 在一行而不是一列中显示 Vuetify 卡?