2

This is my Controller method:

    @RequestMapping(method = RequestMethod.PUT,produces="application/json", headers = "content-type=application/json")
    public @ResponseBody User updateUser(@RequestBody User user) throws PropertyErrorException, ItemNotFoundException {         
        return service.UpdateUser(user);     
    }

Using Spring test-mvc I would like to write a unit test case:

@Test
public void UpdateUser() throws Exception {     
    mockMvc.perform(put("/r01/users").body(userJsonString.getBytes())
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(content().type(MediaType.APPLICATION_JSON))
        .andExpect(content().string(userString));
}

Running this test case generates:

WARN org.springframework.web.servlet.PageNotFound - Request method 'PUT' not supported

Also, updateUser method is never called and the response code is 405.

I have written a lot of tests, all GET requests, and they are working correctly. This means that I am confident in ContextConfiguration. What have I missed?

Jeen Broekstra
  • 21,642
  • 4
  • 51
  • 73
lg.lindstrom
  • 776
  • 1
  • 13
  • 31
  • after one year. having the same issue here. did you mange to do put request? thanks in advance, oak – oak Jan 19 '14 at 10:23
  • ok i got it i was converting to json also getters with no setter. and there for the request was been rejected. my solution for this is skip those kind of getters. i.e :`ObjectMapper mapper = new ObjectMapper(); mapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true); return mapper.writeValueAsBytes(object);` – oak Jan 19 '14 at 11:12

1 Answers1

3

You are explicitly expecting a header of content-type in your @RequestMapping method but not sending the content type in your request, I think that is the reason why the request is failing..try this.

mockMvc.perform(put("/r01/users").contentType(MediaType.APPLICATION_JSON).body(userJsonString.getBytes())
    .accept(MediaType.APPLICATION_JSON))
    .andExpect(status().isOk())
    .andExpect(content().type(MediaType.APPLICATION_JSON))
    .andExpect(content().string(userString));
Biju Kunjummen
  • 49,138
  • 14
  • 112
  • 125