【发布时间】:2012-09-16 23:28:00
【问题描述】:
背景
/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/test/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 配置文件的同时运行测试,就像我在启动 web 应用程序时所做的那样(使用 -P dev)。但我不能让它工作。有可能吗?
附言
过滤后的 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...
【问题讨论】:
-
你的
applicationContext.xml文件过滤后是什么样子的? -
@maba 我应该如何处理才能获得过滤后的?
-
如果你关注了我上次的answer,我向你展示了如何过滤资源。如果您使用
mvn compile构建,您将通过process-resources阶段并且在您的target/classes/文件夹中您将拥有过滤后的资源。 -
@maba 查看我的编辑。感谢您的帮助。在我发布的上一个问题中,我还没有回答你,因为我认为问题来自这些需要激活的 Maven 配置文件。
-
@maba 我让它工作了。事实上,我使用eCobertura 来启动测试,这会产生我发布的错误。我刚刚尝试使用
mvn -Pdev test,它确实有效,因为我可以指定配置文件。有什么方法可以从 eCobertura 启动这个有效的 Maven 命令?
标签: java spring unit-testing maven junit