如何在Spring MVC测试中设置Web应用程序上下文

时间:2013-04-11 04:43:18

标签: spring testing spring-mvc testng

我们在服务层和服务层之间有一个明确的抽象概念。查看图层上下文配置,我们正在加载它们,如下所示。

Root application context:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:META-INF/spring/applicationContext*.xml</param-value>
</context-param>

Web application context:

<servlet>
    <servlet-name>lovemytasks</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/mmapp-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

现在我们正在尝试引入SPRING MVC TEST FRAMEWORK来测试我们的应用程序。

为此,我需要设置与我的真实Web应用程序相同的环境。

我该怎么做?

我在我的测试中尝试了以下配置来加载两个上下文。

@ContextConfiguration(locations = { "classpath*:META-INF/spring/applicationContext*.xml",
    "file:src/main/webapp/WEB-INF/spring/mmapp-servlet.xml" })

但它错误地说

Caused by: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Duplicate <global-method-security> detected. 

我们已在根应用程序上下文和Web应用程序上下文中定义了全局安全性。

注意:运行我的网络应用程序时,上述问题不会出现。它只在我运行Spring MVc测试

时才会发生

我尝试删除全局安全性和一个地方,然后在运行我的测试时使用转换服务登陆错误。这告诫我,我没有像真正的Spring应用程序那样加载上下文。

现在,我想设置我的Spring MVC测试环境,以便像我的Spring Web应用程序环境一样使用或工作。任何人都可以建议我如何实现它?

2 个答案:

答案 0 :(得分:8)

使用@ContextHierarchy注释。它的javadoc描述得很好。在您的情况下,您将使用

@WebAppConfiguration
@ContextHierarchy({
    @ContextConfiguration(locations = { "classpath*:/META-INF/spring/applicationContext-*.xml" }),
    @ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/mmapp-servlet.xml" })
})

答案 1 :(得分:1)

不要将您的appContext放在meta-inf中。

“正常”方式是在web-inf中有一个spring-servlet.xml

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/spring-servlet.xml</param-value>
    </context-param>

Andn然后在xml文件中导入不同的文件:

<import resource="classpath:beans.xml"/>

我为我的测试创建了一个单独的appContent:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations ="classpath:applicationContext-test.xml")
@Transactional
public class MyTest {

您的bean必须在该行的某处加载两次,您是否导入两次bean,在xml中定义它们还是注释?