在Spring webapp中运行JUnit测试时指定Maven配置文件

时间:2012-09-25 12:35:09

标签: java spring unit-testing maven junit

背景

/pom.xml

...
<properties>
    ...
    <jdbc.driver>com.mysql.jdbc.Driver</jdbc.driver>
    <jdbc.url>jdbc:mysql://${database.host}/${database.name}</jdbc.url>
    <jdbc.user>${database.user}</jdbc.user>
    <jdbc.password>${database.password}</jdbc.password>
    ...
</properties>
...
<profiles>
    <profile>
        <id>dev</id>
        <properties>
            ...
            <database.name>database</database.name>
            <database.host>localhost</database.host>
            <database.user>root</database.user>
            <database.password></database.password>
            ...
        </properties>
    </profile>
</profiles>
...

/src/main/resources/database.properties

...
jdbc.driver=${jdbc.driver}
jdbc.url=${jdbc.url}
jdbc.user=${jdbc.user}
jdbc.password=${jdbc.password}
...

/src/main/resources/spring/applicationContext.xml

<beans ... xmlns:p="http://www.springframework.org/schema/p" ...>
    ...
    <bean
        id="dataSource"
        ...
        p:driverClassName="${jdbc.driver}"
        p:url="${jdbc.url}"
        p:username="${jdbc.user}"
        p:password="${jdbc.password}"
        ... />
    ...
</beans>

/ SRC /的测试 /java/com/company/project/service/MyItemServiceImplTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring/applicationContext.xml" })
public class MyItemServiceImplTest {

    @Resource
    private MyItemService myItemService;

    @Test
    public void testSave() {
        MyItem myItem = new MyItem();
        myItemService.save(myItem);
        ...
    }

}

问题

运行测试时,会抛出异常:

java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'dataSource' defined in class path resource [spring/applicationContext.xml]: Could not resolve placeholder 'database.password'
...

我想这是因为我需要在指定dev个人资料时运行测试,就像我启动webapp时一样(使用-P dev)。但我不能让它发挥作用。它甚至可能吗?

PS

过滤后的applicationContext.xml文件(即/target/classes/spring/applicationContext.xml中的文件)与/ src / *中的文件相同,但过滤的database.properties文件(即/ target / classes / database.properties)看起来像

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://${database.host}/${database.name}
jdbc.user=${database.user}
jdbc.password=${database.password}

这意味着从pom.xml文件到.properties文件,属性已经过滤,但在pom.xml本身中,依赖于所选配置文件的属性不会被过滤。可能是因为我想在启动测试时指定我需要的配置文件。但正如我之前所说,-P dev似乎不适用于JUnit ...

1 个答案:

答案 0 :(得分:2)

资源过滤在process-resources阶段执行。因此,如果您声明mvn test -Pdev,您将通过该阶段,并且所有过滤都已完成。 JUnit与您运行的配置文件无关,因为您在dev配置文件中没有做任何其他不同的操作。

相关问题