使用Junit的Spring Test会话作用域bean

我有一个会话范围的Bean,每个http会话都保存用户数据。我想编写一个Junit测试用例来测试会话范围的bean。我想编写测试用例,以便可以证明每个会话都在创建Bean。有什么指针像如何编写这样的Junit测试用例?

回答:

为了在单元测试中使用请求和会话范围,您需要:

  • 在应用程序上下文中注册这些范围
  • 创建模拟会话并请求
  • 通过注册模拟请求 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();

以上是 使用Junit的Spring Test会话作用域bean 的全部内容, 来源链接: utcz.com/qa/420572.html

回到顶部