Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 246
Przemysław Gęsieniec Avatar asked Dec 23 '22 02:12

Przemysław Gęsieniec


1 Answers

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"));
like image 51
Przemysław Gęsieniec Avatar answered Jan 13 '23 21:01

Przemysław Gęsieniec