How to Setup web application context in Spring MVC test
spring, spring-mvc, testing, testng
Solution
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" })
})
Problem
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> ``` Now we are trying to introduce SPRING MVC TEST FRAMEWORK to test our application. For this i would need to setup the same environment as my real web application works. How can i do that ? 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" }) ``` But its erroring out saying ``` Caused by: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Duplicate <global-method-security> detected. ``` We have defined global security in both root application context and web application context. Note: The above said issue will not appear when i run my web application. It happens only when i run Spring MVc test 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. 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 ?