我有一个会话范围的Bean,每个http会话都保存用户数据。我想编写一个Junit测试用例来测试会话范围的bean。我想编写测试用例,以便可以证明每个会话都在创建Bean。有什么指针像如何编写这样的Junit测试用例?
为了在单元测试中使用请求和会话范围,您需要:
RequestContextHolder
这样的事情(假设您使用Spring TestContext运行测试) abstractSessionTest.xml:
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; } }
现在,您可以在测试代码中使用以下方法:
startSession(); startRequest(); // inside request endRequest(); startRequest(); // inside another request of the same session endRequest(); endSession();