【问题标题】:How to use testng to test serivce with session read and write?如何使用 testng 通过会话读写测试服务?
【发布时间】:2012-12-20 14:11:01
【问题描述】:

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

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

【问题讨论】:

    标签: spring session testng


    【解决方案1】:

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

    【讨论】:

    • 我认为它不是不能获得价值但不能这样做
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多