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


The Servlet container decides when to dispatch events to the 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 listener = new MyHttpSessionListener();

outside the context of your application.

Leave a Reply

Your email address will not be published. Required fields are marked *