Java 为 Junit 测试构建简单的 http-header
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18889688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Building simple http-header for Junit test
提问by tokhi
I'm trying to test a HttpServletRequest
and for that I have used Mockitoas follow:
我正在尝试测试一个HttpServletRequest
,为此我使用了 Mockito,如下所示:
HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class);
now before putting the http-request in assert
methods I just want to build a simple http header as below without starting a real server:
现在,在将 http 请求放入assert
方法之前,我只想构建一个简单的 http 标头,如下所示,而无需启动真正的服务器:
x-real-ip:127.0.0.1
host:example.com
x-forwarded-for:127.0.0.1
accept-language:en-US,en;q=0.8
cookie:JSESSIONID=<session_ID>
can some one help how can I build such a test header? thanks.
有人可以帮助我如何构建这样的测试头吗?谢谢。
回答by blank
You can just stub the calls to request.getHeaders etc. or if you can add a dependency, Spring-testhas a MockHttpServletRequest
that you could use (see here)
您可以仅存根对 request.getHeaders 等的调用,或者如果您可以添加依赖项,Spring-test有一个MockHttpServletRequest
您可以使用的(请参见此处)
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("x-real-ip","127.0.0.1");
Or you could build your own implementation which allows you to set headers.
或者您可以构建自己的实现,允许您设置标题。
回答by prax
The above answer uses MockHttpServletRequest
.
If one would like to use Mockito.mock(HttpServletRequest.class)
, then could stub the request as follows.
上面的答案使用MockHttpServletRequest
. 如果想使用Mockito.mock(HttpServletRequest.class)
,则可以按如下方式存根请求。
final HttpServletResponse response = mock(HttpServletResponse.class);
when(request.getHeader("host")).thenReturn("stackoverflow.com");
when(request.getHeader("x-real-ip")).thenReturn("127.0.0.1");