I have a session scoped bean which holds user data per http session. I would like to write a Junit test case to test the session scoped bean. I would like to write the test case such that it can prove that the beans are getting created per session. Any pointer as how to write such Junit test case?
In order to use request and session scopes in unit test you need to:
RequestContextHolder
Something like this (assume that you use Spring TestContext to run your tests): abstractSessionTest.xml
:
<beans ...> <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer"> <property name="scopes"> <map> <entry key="session"> <bean class="org.springframework.web.context.request.SessionScope" /> </entry> <entry key="request"> <bean class="org.springframework.web.context.request.RequestScope" /> </entry> </map> </property> </bean> </beans>
.
@ContextConfiguration("abstractSessionTest.xml") public abstract class AbstractSessionTest { protected MockHttpSession session; protected MockHttpServletRequest request; protected void startSession() { session = new MockHttpSession(); } protected void endSession() { session.clearAttributes(); session = null; } protected void startRequest() { request = new MockHttpServletRequest(); request.setSession(session); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); } protected void endRequest() { ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).requestCompleted(); RequestContextHolder.resetRequestAttributes(); request = null; } }
Now you can use these methods in your test code:
startSession(); startRequest(); // inside request endRequest(); startRequest(); // inside another request of the same session endRequest(); endSession();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With