tokhi
tokhi

Reputation: 21618

Building simple http-header for Junit test

I'm trying to test a HttpServletRequest and for that I have used Mockito as follow:

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:

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.

Upvotes: 10

Views: 24185

Answers (2)

prax
prax

Reputation: 61

The above answer uses MockHttpServletRequest. If one would like to use Mockito.mock(HttpServletRequest.class) , then could stub the request as follows.

final HttpServletResponse response = mock(HttpServletResponse.class);
when(request.getHeader("host")).thenReturn("stackoverflow.com");
when(request.getHeader("x-real-ip")).thenReturn("127.0.0.1");

Upvotes: 0

blank
blank

Reputation: 18170

You can just stub the calls to request.getHeaders etc. or if you can add a dependency, Spring-test has a MockHttpServletRequest that you could use (see here)

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.

Upvotes: 14

Related Questions