我有一个会话范围的 bean,它保存每个 http 会话的用户数据。我想编写一个 Junit 测试用例来测试会话范围的 bean。我想编写测试用例,以便它可以证明每个会话都创建了 bean。有关如何编写此类 Junit 测试用例的任何指针?
问问题
27923 次
3 回答
30
为了在单元测试中使用请求和会话范围,您需要:
- 在应用程序上下文中注册这些范围
- 创建模拟会话和请求
- 通过注册模拟请求
RequestContextHolder
像这样的东西(假设你使用 Spring TestContext 来运行你的测试)
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();
于 2011-02-28T09:14:27.250 回答
30
我遇到了这种更简单的方法,我想我不妨在这里发帖以防其他人需要它。
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="session">
<bean class="org.springframework.context.support.SimpleThreadScope"/>
</entry>
</map>
</property>
</bean>
使用这种方法,您不必模拟任何请求/会话对象。
资料来源:http ://tarunsapra.wordpress.com/2011/06/28/junit-spring-session-and-request-scope-beans/
于 2012-01-10T12:19:38.060 回答
12
Spring 3.2 和更新版本为集成测试提供了对会话/请求范围 bean 的支持
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class)
@WebAppConfiguration
public class SampleTest {
@Autowired WebApplicationContext wac;
@Autowired MockHttpServletRequest request;
@Autowired MockHttpSession session;
@Autowired MySessionBean mySessionBean;
@Autowired MyRequestBean myRequestBean;
@Test
public void requestScope() throws Exception {
assertThat(myRequestBean)
.isSameAs(request.getAttribute("myRequestBean"));
assertThat(myRequestBean)
.isSameAs(wac.getBean("myRequestBean", MyRequestBean.class));
}
@Test
public void sessionScope() throws Exception {
assertThat(mySessionBean)
.isSameAs(session.getAttribute("mySessionBean"));
assertThat(mySessionBean)
.isSameAs(wac.getBean("mySessionBean", MySessionBean.class));
}
}
参考:
于 2014-01-30T13:26:42.970 回答