簡體   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