繁体   English   中英

在 JUnit 测试中使用来自 src/main/resources 的实际属性文件和 Spring @PropertySource

[英]Using actual properties file from src/main/resources with Spring @PropertySource in JUnit test

我正在尝试使用 H2 数据库而不是实际数据库对 DAO class 进行单元测试。 我在尝试让我的测试用例使用src/main/resources/properties/文件夹中存在的属性文件时遇到问题:

测试 class

@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>

当我运行测试 class 时,出现以下异常:

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}"

测试用例无法找到所需属性的原因之一是:

  1. PropertyPlaceholderConfigurer bean 引用{conf_folder_path}/common.properties ,这是src/main/resources/properties/common.properties被 Maven 构建系统复制到的路径。
  2. 但是,在 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();
    }

感谢@Lemmy指导如何解决这个问题。

我的最终解决方案是创建一个新common-test-context.xml文件,我可以在其中查找 class 路径的属性文件夹中的属性文件。 我将此文件放在src/test/resources/spring文件夹中,并将实际的common-context.xmlsrc/main/resources/spring文件夹导入其中。

<?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">

    <import resource="classpath*:/spring/common-context.xml" />


    <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>classpath:/properties/common.properties</value>
            </list>
        </property>
    </bean>

</beans>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM