spring mvc 3 content-type “application/json” works

2019-03-28 22:32发布

I have a Rest Controller method using Spring 3.1 that looks like this:

@RequestMapping(value="/user", method=RequestMethod.POST, consumes={MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<String> addUser(@RequestBody @Valid User user){   
    System.out.println("called / user method");
      try{
        user = userService.addUser(user); 
        return responseBuilder.addApiResourceSucceeded(user,null);
      }catch(Exception e){
        return responseBuilder.apiActionFailed("user already exists", HttpStatus.CONFLICT);  
      }
}

I have test which looks like this:

@Before
public void setUp() {
    adapter = new AnnotationMethodHandlerAdapter();
    request = new MockHttpServletRequest();
    response = new MockHttpServletResponse();
    mapper = new ObjectMapper();
}
@Test
public void testAddUser() throws Exception {
    request.setMethod("POST");
    request.setContentType(MediaType.APPLICATION_JSON_VALUE);
    request.setRequestURI("/user");

    ObjectNode userJson = mapper.createObjectNode();
    userJson.put("userId", "jonnybz");
    userJson.put("email", "test@gmail.com");
    userJson.put("password", "password");
    userJson.put("longitude",-10.127205999);
    userJson.put("latitude", 57.252269);
    ArrayNode arrNode = mapper.createArrayNode();
    arrNode.add(-10.1272059999);
    arrNode.add(57.2522);
    userJson.put("lonLat",arrNode);
    request.setContent(mapper.writeValueAsBytes(userJson));
    adapter.handle(request, response, userController); 

    String content = response.getContentAsString();
    assertEquals(200, response.getStatus());
    User user = dao.listAll().get(0);
    objectId = user.getId();
    assertNotNull(objectId);
}

When I execute a call against this endpoint from my client app (developed with angular) it works great, but when I run my test I get an " Content type 'application/json' which is coming from a HttpMediaTypeNotSupportedException" error that I cannot track down. The request never seems to hit my method. Am I missing something simple here?

Solved this problem by switching to the spring-mvc-test framework and building my test like this:

@Test
public void testAddUser() throws Exception {

    ObjectNode userJson = mapper.createObjectNode();
    userJson.put("userId", "jonnbz");
    userJson.put("email", "test@gmail.com");
    userJson.put("password", "password");
    userJson.put("longitude",-10.667205999);
    userJson.put("latitude", 74.252269);
    ArrayNode arrNode = mapper.createArrayNode();
    arrNode.add(-10.667205999);
    arrNode.add(74.252269);
    userJson.put("lonLat",arrNode);
    MvcResult res = MockMvcBuilders.xmlConfigSetup("classpath:test-context.xml").build()
           .perform(MockMvcRequestBuilders.post("/user")
           .accept(MediaType.APPLICATION_JSON)
           .contentType(MediaType.APPLICATION_JSON)
           .body(mapper.writeValueAsBytes(userJson)))
           .andExpect(status().isOk())
           .andExpect(content().type(MediaType.APPLICATION_JSON))
           .andReturn();
            System.out.println(res.getResponse().getContentAsString());

}

1条回答
男人必须洒脱
2楼-- · 2019-03-28 23:06

You should also include a Accept header of "application/json" in your test, since you have included a consumes="application/json", Spring MVC will match the Accept header value to the consumes value and only then call the mapped method.

查看更多
登录 后发表回答