正确设置RequestBody的MockHttpServletRequestBuilder

时间:2014-02-27 17:45:38

标签: java spring-mvc

我只是尝试使用MockHttpServletRequestBuilder测试Spring控制器方法。控制器方法的签名如下所示:

 @RequestMapping(value = "/assignTeamsToUsers", method = RequestMethod.POST)
 public @ResponseBody String assignUsersToTeams(Model model, @RequestBody MultiValueMap<String, String> ids).

在我的测试案例中,我有:

MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(applicationContext).build();
MockHttpServletRequestBuilder request = createRequest(uri, method);

//set up request object...Not sure how??
//My current attempt:
     String body = "userIds[]=0&teamIds[]=0";
     request.content(body);
     request.accept(MediaType.ALL);
     request.contentType(MediaType.APPLICATION_FORM_URLENCODED);

ResultActions resultActions = mockMvc.perform(request);

编辑:显示createRequest。 method =“POST”

private MockHttpServletRequestBuilder createRequest (String uri, String method) {
    MockHttpServletRequestBuilder builder = null;

    if("GET".equalsIgnoreCase(method))
        builder = MockMvcRequestBuilders.get(uri);
    else if("POST".equalsIgnoreCase(method))
        builder = MockMvcRequestBuilders.post(uri);
    else
        Assert.fail("Unsupported method!");

    //We always create requests for user Manager
    builder.header("securityRole", Role.Manager.getDisplayName());

    return builder;

}

我知道uri和方法是正确的。我的问题是我从Spring获得了 415 错误代码。基本上,我不知道如何设置request对象以使@RequestBody具有适当的MultiValueMap。我已经尝试了很多设置request.content的变体,设置request.accept,request.contentType,request.characterEncoding,并且仍然每次我得到415错误。

如果有任何帮助,我可以使用网络界面成功发布到此终端,以下是chrome中的请求:

enter image description here

1 个答案:

答案 0 :(得分:5)

我最后通过以下方式解决了这个问题:

MockHttpServletRequestBuilder request = MockMvcRequestBuilders.post("whatever url");
request.contentType(MediaType.APPLICATION_FORM_URLENCODED);

//set key value pairs
//also the keys do not have to be unique, two keys of the same value will both get added 
request.param("key", "value");

MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(applicationContext).build();
ResultActions resultActions = mockMvc.perform(request);
// make sure response is valid

希望这可以引导别人朝着正确的方向前进。 感谢