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

Shi*_*hiv 6 testing testng spring spring-mvc

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

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>
Run Code Online (Sandbox Code Playgroud)

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

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

我怎样才能做到这一点 ?

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

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

但它错误地说出来了

Caused by: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Duplicate <global-method-security> detected. 
Run Code Online (Sandbox Code Playgroud)

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

注意:运行我的Web应用程序时,上述问题不会出现.它只在我运行Spring MVc测试时才会发生

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

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

sbk*_*sbk 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" })
})
Run Code Online (Sandbox Code Playgroud)