如何在Maven测试中加载Spring Application上下文

时间:2013-01-17 09:30:49

标签: spring maven junit junit4

我有一个 Maven web项目,我想执行一些JUnit集成测试。为此,我想加载 applicationContext.xml 文件以获取Spring注入的bean。我的应用程序上下文文件也位于src/main/resources/app_context,但在执行Maven的生命周期时,它将它们定位到WEB-INF/classes/application_context,因此我可以通过类路径访问它们。

<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的目标测试目录中:

<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将它们复制到测试和执行范围。但是我的测试类无法找到并加载它们。我该怎么办?

1 个答案:

答案 0 :(得分:2)

假设您的applicationContext.xml位于src/main/resources/appcontext,Maven默认会在WEB-INF/classes/appcontext中对其进行重新定位。没有必要为该资源分配新路径。

您应该能够在测试中找到上下文文件:

@ContextConfiguration(locations={"/appcontext/applicationContext.xml"})

您不需要额外的Maven设置。