我有一个Maven web项目我想执行一些JUnit集成测试。为了实现这一点,我想加载applicationContext.xml文件来获取Spring注入的bean。此外,我的应用程序上下文文件位于src/main/resources/app_context
中,但执行Maven的生命周期时,它将它们定位到WEB-INF/classes/application_context
,因此我可以通过类路径访问它们。如何在Maven测试中加载Spring应用程序上下文
<resource>
<directory>src/main/resources/appcontext</directory>
<targetPath>${basedir}/src/main/webapp/WEB-INF/classes/application_context</targetPath>
<filtering>true</filtering>
<includes>
<include>*/**</include>
</includes>
</resource>
我试图在某些方面访问该上下文,但没有成功。我也把它们放入Maven的目标test目录那样:
<testResources>
<testResource>
<directory>
src/main/resources/appcontext
</directory>
<targetPath>${basedir}/src/main/webapp/WEB-INF/classes/application_context</targetPath>
</testResource>
</testResources>
这是我的一块试验:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:**/applicationContext.xml" })
@Transactional
public class SystemTest {
@Autowired
ApplicationContext applicationContext;
@Test
public void initializeSystemTest() {
//Test code
这就是我如何可以访问应用程序上下文的其余部分从我的主要文件之一:
<?xml version="1.0" encoding="ISO-8859-15"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:cxf="http://cxf.apache.org/core" xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<import resource="classpath:application_context/ApplicationContext*.xml" />
<context:annotation-config />
<!--========== Spring Data Source ========== -->
<!--Bean stuff-->
基本上我想只有一个存储在src/main/resources
ApplicationContext的文件中的每一个副本,让Maven的复制他们的测试和exec范围。但是我的测试类无法找到并加载它们。我必须做什么?
你为什么要从'appcontext'复制到'application_context'?这只会混淆问题。为什么不使用默认值,在这种情况下,'src/main/resources/appcontext'会在'WEB-INF/classes/appcontext'中结束?在你的SCM上它也会更容易,因为你在构建时不会因'src'的变化而结束。 – artbristol
好点@artbristol。 –