对依赖于请求上下文的方法进行单元测试 [英] Unit testing a method dependent to the request context

查看:285
本文介绍了对依赖于请求上下文的方法进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为包含以下行的方法编写单元测试:

I'm writing a unit test for a method that contains the following line:

String sessionId = RequestContextHolder.currentRequestAttributes().getSessionId();

我收到以下错误:

java.lang.IllegalStateException:找不到线程绑定的请求:是 您指的是实际网络请求之外的请求属性, 或在原始接收线程之外处理请求?如果 您实际上是在网络请求中进行操作,但仍然收到此请求 消息,您的代码可能正在外部运行 DispatcherServlet/DispatcherPortlet:在这种情况下,请使用 RequestContextListener或RequestContextFilter公开当前 请求.

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.

原因很明显-我不在请求上下文中运行测试.

The reason is quite obvious — I'm not running the test in a request context.

问题是,如何在测试环境中测试包含对依赖于请求上下文的方法的调用的方法?

The question is, how can I test a method that contains a call to a method dependent to the request context in a test environnment?

非常感谢您.

推荐答案

Spring-test有一个名为MockHttpServletRequest的灵活请求模拟.

Spring-test has a flexible request mock called MockHttpServletRequest.

MockHttpServletRequest request = new MockHttpServletRequest();
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));

这篇关于对依赖于请求上下文的方法进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆