MockHttpServletRequestBuilder-如何更改HttpServletRequest的remoteHost的remoteAddress?

时间:2018-12-06 16:10:05

标签: java spring-mvc spring-boot spring-boot-test mockmvc

我正在尝试为集成测试创建模拟请求(@SpringBootTest)。

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

我要检查的是此请求的远程地址。在我的控制器中,我从 HttpServletRequest

获取此信息
HttpServletRequest request;
request.getRemoteHost();
request.getRemoteAddr();

不幸的是,getRemoteHost()现在将始终返回 localhost

我想在模拟请求中将其更改为其他内容,例如:

  

remoteHost:localhost-> mockhostdomain

     

remoteAddr:127.0.0.1-> 10.32.120.7(不一样)

我找不到合适的方法。 有可能吗?

2 个答案:

答案 0 :(得分:2)

我终于在这里找到了解决方案:

  

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

基本上,通过这种方法,我们可以更改请求的每个参数。

因此,首先我们必须定义我们的方法,该方法会更改请求中所需的内容:

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

与在with(...)对象上使用方法MockHttpServletRequestBuilder相比,我们必须注入此方法结果。

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

答案 1 :(得分:0)

使用mockmvc,您可以这样做:

        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);