如何在 Spring MVC 测试中设置 Web 应用程序上下文 [英] How to Setup web application context in Spring MVC test
问题描述
我们在服务层和服务层之间有清晰的抽象查看层上下文配置,我们正在加载它们,如下所示.
We have a clear abstraction between Service layers & view layers context configurations and we are loading them as shown below.
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 来测试我们的应用程序.
Now we are trying to introduce SPRING MVC TEST FRAMEWORK to test our application.
为此,我需要设置与真实 Web 应用程序相同的环境.
For this i would need to setup the same environment as my real web application works.
我该怎么做?
我在测试中尝试了以下配置以加载两个上下文.
I tried below configuration on my test to load both the contexts.
@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 应用程序上下文中都定义了全局安全性.
We have defined global security in both root application context and web application context.
注意:当我运行我的 Web 应用程序时,不会出现上述问题.它仅在我运行 Spring MVc 测试时发生
我尝试删除我的全局安全性和一个地方,然后在运行我的测试时遇到转换服务错误.这警告我,我没有像真正的 Spring 应用程序那样加载上下文.
I tried removing my global security and one place and then landing into errors with conversion services on running my tests. Which warned me that I am not loading the context as teh real Spring application does.
现在,我想设置我的 Spring MVC 测试环境,使其使用或工作方式与我的 Spring Web 应用程序环境的工作方式相同.任何人都可以建议我如何实现它?
Now, i would like to setup my Spring MVC test environment to use or work as the same way my spring web application environment works. Can any one please suggest how can i achieve it ?
推荐答案
使用 @ContextHierarchy 注释.它的 javadoc 很好地描述了它.在您的情况下,您将使用
Use the @ContextHierarchy annotation. Its javadoc describes it well. In your case you would use
@WebAppConfiguration
@ContextHierarchy({
@ContextConfiguration(locations = { "classpath*:/META-INF/spring/applicationContext-*.xml" }),
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/mmapp-servlet.xml" })
})
这篇关于如何在 Spring MVC 测试中设置 Web 应用程序上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!