我的服务需要从会话中获取对象:
@Service("UsageService")
@Scope(value="session")
public class UsageServiceImpl implements UsageService
{
@Override
public void doAnalysis()
{
// get data from session
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession();
......
}
}
像这样测试代码
@ContextConfiguration(locations = { "test-context.xml" })
@Transactional
public class UsageServiceImplTest extends AbstractTestNGSpringContextTests
{
@Autowired
private UsageService service;
@Test
public void testAnalysis()
{
service.doAnalysis(null);
}
}
我已按照http://tarunsapra.wordpress.com/2011/06/28/junit-spring-session-and-request-scope-beans/的建议将此添加到test-context.xml
<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>
当我运行文本时出现此错误:
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
正如错误消息所示:由于我通过testng启动服务而不是http请求,我在实际Web请求之外引用请求属性,如何使用会话读写可测试服务?
答案 0 :(得分:0)
您可以在单元测试中使用mockito来模拟RequestAttributes对象以返回您想要的内容,然后在开始测试之前使用您的模拟/存根调用RequestContextHolder.setRequestAttributes(RequestAttributes)。