gpt4 book ai didi

integration - web.xml 中的 Spring-test 和 ServletContextListener

转载 作者:行者123 更新时间:2023-12-02 14:13:43 32 4
gpt4 key购买 nike

我尝试使用 spring-test(3.2.10) 并通过 TestNG 进行集成测试 link .

我创建了 RootTest.java

@WebAppConfiguration
@ContextConfiguration("file:src/test/resources/root-context2.xml")
public class ReferenceServiceTest extends AbstractTestNGSpringContextTests {
...

spring 上下文加载成功。但我的全局变量没有实例化,因为 web.xml 被忽略。在 web.xml 中,我有自己的“监听器类”(ServletContextListener 的实现)和“上下文参数”。我如何使用 Spring 集成测试上下文加载 web.xml 上下文(并调用所有应用程序启动监听器)?

最佳答案

正如引用手册中所述,Spring MVC 测试框架...

"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."

关键点是“没有...... Servlet容器”。因此web.xml此处不涉及。也就是说,web.xml中没有办法进行配置。对使用 Spring MVC 测试框架的集成测试产生影响。

话虽如此,现在可以注册一个 Servlet FilterMockMvc像这样:

mockMvcBuilder.addFilters(myServletFilter);

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

并且您可以配置context-param手动将条目添加到ServletContext (实际上是 Spring 的 MockServletContext )在 MockMvc 上执行断言之前像这样:

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

但是...没有办法配置 ServletContextListener使用 Spring MVC 测试。如果您希望将一个监听器应用于通过 Spring MVC 传递的所有请求,作为替代方案,您可以考虑实现自定义 HandlerInterceptorWebRequestInterceptor (请参阅引用手册中的Configuring interceptors)。

问候,

山姆

关于integration - web.xml 中的 Spring-test 和 ServletContextListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25329160/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com