Przemysław Gęsieniec
Przemysław Gęsieniec

Reputation: 648

MockHttpServletRequestBuilder - how to change remoteAddress of remoteHost of HttpServletRequest?

I'm trying to create mock request for integration test (@SpringBootTest).

//given     
MockHttpServletRequestBuilder requestBuilder = get("/users/register/user1");

What I want to check is the remote of this request. In my controller Im getting this information from HttpServletRequest

HttpServletRequest request;
request.getRemoteHost();
request.getRemoteAddr();

Unfortunately right now getRemoteHost() will always return localhost.

I would like to change it in my mock request to something else eg:

remoteHost: localhost --> mockhostdomain

remoteAddr: 127.0.0.1 --> 10.32.120.7 (anything different)

I cannot find proper method for that. Is it even possible?

Upvotes: 8

Views: 5282

Answers (2)

Przemysław Gęsieniec
Przemysław Gęsieniec

Reputation: 648

I have finally found solution for that here:

https://techotom.wordpress.com/2014/11/12/mocking-remoteaddr-with-spring-mvc/

Basically with this method we can change every parameter of request.

So at first we have to define our method which changes what we want in the request:

private static RequestPostProcessor remoteHost(final String remoteHost) {
    return request -> {
        request.setRemoteHost(remoteHost);
        return request;
    };
}

And then with method with(...) on MockHttpServletRequestBuilder object we have to inject this method outcome.

 MockHttpServletRequestBuilder requestBuilder = get("/user/prop").
         .with(remoteHost("mockhostdomain.com"));

Upvotes: 14

keith5140
keith5140

Reputation: 1394

with mockmvc you can do like this:

        Map<String, String> req = new HashMap<>();
//        req.put("")
        ObjectMapper mapper = new ObjectMapper();
        ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
        java.lang.String requestJson = ow.writeValueAsString(req);

        String responseString = this.mockMvc.perform(post
                ("/authorization/activated")
                .with(request->{request.setRemoteAddr("192.168.0.2");return request;})
                .contentType(MediaType.APPLICATION_JSON)
                .content(requestJson)
                .header("Authorization", bear)
        .header("X-Device-Id","7fb0c4e49aec4c5a9a089d0c84f7078b"))
                .andReturn().getResponse().getContentAsString();
        System.out.println("[POST result]:" + responseString);

Upvotes: 4

Related Questions