简体   繁体   English

是否可以使用Spring-MVC和Spring-Test-MVC测试HttpSessionListener?

[英]Is it possible to test an HttpSessionListener with Spring-MVC and Spring-Test-MVC?

We have some logic in an HttpSessionListener that we'd like to test. 我们需要测试HttpSessionListener中的一些逻辑。 We're using Spring MVC and the associated testing framework, with MockMvc and so on. 我们正在使用Spring MVC和相关的测试框架,以及MockMvc等。 Unfortunately, we haven't found a way to get the listener initialized so that when a session is created or destroyed the appropriate listener methods are called. 不幸的是,我们还没有找到一种初始化监听器的方法,以便在创建或销毁会话时调用适当的监听器方法。

I have tried to add the listener programmatically rather than using web.xml (as described in this question ) and this works fine when running in a Servlet 3.0 container. 我试图以编程方式添加侦听器,而不是使用web.xml (如本问题所述 ),并且在Servlet 3.0容器中运行时可以正常工作。 But when running with Spring Test it all goes wrong, as the MockServletContext does not support the addListener method , and so throws an exception. 但是当使用Spring Test运行时,一切都会出错,因为MockServletContext 不支持addListener方法 ,因此会引发异常。

Is there any way to test such listeners without using integration testing? 有没有办法在不使用集成测试的情况下测试此类侦听器?

The Servlet container decides when to dispatch events to the HttpSessionListener . Servlet容器决定何时将事件调度到HttpSessionListener This is not necessarily right after a session created or destroyed. 创建或销毁会话后,这不一定是正确的。 Because this depends on the container implementation, you can't depend on the unit test. 因为这取决于容器的实现,所以您不能依赖于单元测试。 Integration testing is the way to go. 集成测试是必经之路。

You can always unit test those HttpSessionListener implementations 您始终可以对这些HttpSessionListener实现进行单元测试

HttpSessionListener listener = new MyHttpSessionListener();
listener.sessionCreated(mockEvent);
listener.sessionDestroyed(mockEvent);

outside the context of your application. 在您的应用程序上下文之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM