Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Test session scope bean using Junit

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?

like image 369
Shamik Avatar asked Feb 27 '11 23:02

Shamik


1 Answers

In order to use request and session scopes in unit test you need to:

  • register these scopes in application context
  • create mock session and request
  • register mock request via 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(); 
like image 60
axtavt Avatar answered Oct 03 '22 00:10

axtavt