Использование файла фактических свойств из src / main / resources с Spring @PropertySource в тесте JUnit - PullRequest
1 голос
/ 08 апреля 2020

Я пытаюсь провести модульное тестирование класса DAO, используя базу данных H2 вместо реальной базы данных. Я столкнулся с проблемой при попытке заставить мой тестовый пример использовать файл свойств, который находится в папке 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
}

common-context. 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}"

Одна причина для тестового случая не возможность найти требуемое свойство объясняется тем, что:

  1. Компонент PropertyPlaceholderConfigurer ссылается на {conf_folder_path}/common.properties - путь, по которому src/main/resources/properties/common.properties копируется системой сборки Maven.
  2. Однако в Eclipse нет {conf_folder_path}, поскольку он создан Maven.

Вопрос: Если предположить, что вышеуказанная причина является причиной root, как мне сделать, чтобы тестовый случай нашел свойства, учитывающие путь, на который ссылается Spring контекст отличается от этого в исходном коде.

Ответы [ 2 ]

1 голос
/ 08 апреля 2020

Вы можете создать что-то вроде этого:

@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();
    }
0 голосов
/ 08 апреля 2020

Спасибо @ Lemmy за руководство по решению этой проблемы.

Мое окончательное решение состояло в том, чтобы создать новый файл common-test-context.xml, в котором я могу найти файл свойств в папке свойств на пути к классам. Я поместил этот файл в папку src/test/resources/spring и импортировал в нее фактическую папку common-context.xml из папки src/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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...