如何使用testng通过会话读写来测试服务?

时间:2012-12-20 05:41:27

标签: spring session testng

我的服务需要从会话中获取对象:

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

1 个答案:

答案 0 :(得分:0)

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