Spring-test and ServletContextListener in web.xml

[亡魂溺海] 提交于 2019-12-04 10:59:35

As stated in the reference manual, the Spring MVC Test Framework...

"loads the actual Spring configuration through the TestContext framework and always uses the DispatcherServlet to process requests thus approximating full integration tests without requiring a running Servlet container."

The key point there is "without ... a Servlet container". Thus web.xml does not come into the picture here. In other words, there is no way for configuration in web.xml to have an affect on integration tests using the Spring MVC Test Framework.

Now, having said that, it is possible to register a Servlet Filter with MockMvc like this:

mockMvcBuilder.addFilters(myServletFilter);

or

mockMvcBuilder.addFilters(myResourceFilter, "/resources/*");

And you can configure context-param entries by adding them manually to the ServletContext (which is actually Spring's MockServletContext) before you execute assertions on MockMvc like this:

wac.getServletContext().setInitParameter(name, value);

But... there is no way to configure a ServletContextListener using Spring MVC Test. If you want to have a listener applied to all of your requests that pass through Spring MVC, as an alternative you could consider implementing a custom HandlerInterceptor or WebRequestInterceptor (see Configuring interceptors in the reference manual).

Regards,

Sam

Try with a MockServletContext

@Before
public void before() {
    MockServletContext mockServletContext = new MockServletContext();
    mockServletContext.setInitParameter("parameterName", "parameterValue");
    new MyListenerClass().contextInitialized(new ServletContextEvent(mockServletContext));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!