Setting RequestBody properly of MockHttpServletRequestBuilder

java, spring-mvc

Solution

I ended up solving this by doing the following:

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

Hope this can lead someone else in the right direction. Thanks

Problem

I am simply trying to test a Spring controller method using a `MockHttpServletRequestBuilder`. The signature of the controller method looks like this: ``` @RequestMapping(value = "/assignTeamsToUsers", method = RequestMethod.POST) public @ResponseBody String assignUsersToTeams(Model model, @RequestBody MultiValueMap<String, String> ids). ``` In my test case I have: ``` 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); ``` EDIT: Showing 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; } ``` I know the uri and method are correct. My problem is I am getting a 415 error code from Spring. Basically, I do not know how to set up the `request` object to have the appropriate `@RequestBody` for the `MultiValueMap`. I have tried alot of variations of setting request.content, setting the request.accept, request.contentType, request.characterEncoding, and still every time I get a 415 error. If it is any help, I can successfully Post to this endpoint using the web interface, and here is what the request looks like in chrome:

Original source