问题描述
我尝试通过链接.
我创建了RootTest.java
I created RootTest.java
@WebAppConfiguration
@ContextConfiguration("file:src/test/resources/root-context2.xml")
public class ReferenceServiceTest extends AbstractTestNGSpringContextTests {
...
spring上下文加载成功.但是我的全局变量没有实例化,因为web.xml被忽略了.在web.xml中,我有自己的侦听器类"(ServletContextListener的实现)和"context-param".如何使用Spring Integration Test上下文加载web.xml上下文(并调用所有应用程序启动侦听器)?
spring context loaded success. But my global variables not instantiated because web.xml ignored. In web.xml i have my own "listener-class"(implementation of ServletContextListener) and "context-param". How i can load web.xml context(and calls all application startup listeners) with spring integration test context?
推荐答案
如参考手册中所述,Spring MVC测试框架...
As stated in the reference manual, the Spring MVC Test Framework...
关键点是没有... Servlet容器".因此,web.xml
不在此处显示.换句话说,web.xml
中的配置无法影响使用Spring MVC测试框架的集成测试.
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.
现在,话虽如此,可以这样向MockMvc
注册Servlet Filter
:
Now, having said that, it is possible to register a Servlet Filter
with MockMvc
like this:
mockMvcBuilder.addFilters(myServletFilter);
或
mockMvcBuilder.addFilters(myResourceFilter, "/resources/*");
您可以通过在MockMvc
上执行断言之前将它们手动添加到ServletContext
(实际上是Spring的MockServletContext
)来配置context-param
条目:
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);
但是...无法使用Spring MVC Test配置ServletContextListener
.如果您希望对通过Spring MVC传递的所有请求应用 listener ,作为替代方案,您可以考虑实现自定义HandlerInterceptor
或WebRequestInterceptor
(请参见配置拦截器,请参阅参考手册.
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).
此致
山姆
这篇关于web.xml中的Spring-test和ServletContextListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!