0

我的服务需要从会话中获取对象,如下所示:

  @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 请求之外引用请求属性,如何使会话读写可测试的服务?

4

1 回答 1

0

您可以在单元测试中使用 mockito 来模拟 RequestAttributes 对象以返回您想要的内容,然后在开始测试之前使用您的模拟/存根调用 RequestContextHolder.setRequestAttributes(RequestAttributes)。

于 2012-12-20T06:11:01.677 回答