2

We have some logic in an HttpSessionListener that we'd like to test. We're using Spring MVC and the associated testing framework, with MockMvc and so on. 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. But when running with Spring Test it all goes wrong, as the MockServletContext does not support the addListener method, and so throws an exception.

Is there any way to test such listeners without using integration testing?

4

1 回答 1

4

Servlet 容器决定何时将事件分派到HttpSessionListener. 这不一定是在会话创建或销毁之后。因为这取决于容器实现,所以不能依赖单元测试。集成测试是要走的路。

您始终可以对这些HttpSessionListener实现进行单元测试

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

在您的应用程序的上下文之外。

于 2013-08-30T15:06:21.927 回答