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


问题内容

我们在服务层和视图层上下文配置之间有一个清晰的抽象,我们正在按如下所示加载它们。

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应用程序上下文中定义了全局安全性。

注意:当我运行Web应用程序时,上述问题不会出现。 仅当我运行Spring MVc测试时才会发生

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

现在,我想设置我的Spring MVC测试环境,使其以与Spring Web应用程序环境相同的方式使用或工作。有人可以建议我如何实现吗?


问题答案:

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

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