当 ResponseBody 有集合时,MockMvc post junit 测试返回 415

mer*_*ksu 2 java spring spring-mvc spring-boot mockmvc

我正在使用 mockmvc 进行休息服务集成测试。我有一个 post rest 服务,从 postman 调用它并得到 200 但是当我用 mockmvc porform 方法调用它时返回 415 unsupported media type 异常。

休息法

@RequestMapping(value = "/users/test/{groupId}",
        method = RequestMethod.POST,
        produces=MediaType.APPLICATION_JSON_VALUE,
        consumes=MediaType.APPLICATION_JSON_VALUE)
private GenericResponse postTest(@PathVariable("groupId")String groupId,@RequestBody List<Contact> test, @RequestHeader("Authorization")String authorization) {
    return new GenericResponse();
}
Run Code Online (Sandbox Code Playgroud)

测试方法

@Test
public void testPost() throws Exception {
    Contact contact = new Contact();
    contact.setName("contact1");
    contact.setMsisdn("901234567890");

    Contact contact2 = new Contact();
    contact2.setName("contact2");
    contact2.setMsisdn("901234567890");

    List<Contact> contactList = new ArrayList<>();
    contactList.add(contact);
    contactList.add(contact2);

    Gson gson = new Gson();
    String request = gson.toJson(contactList);

    MvcResult result = mvc.perform(
            post("/users/test/{groupId}","123")
                    .with(httpBasic(username,password))
                    .contentType(MediaType.APPLICATION_JSON_VALUE)
                    .accept(MediaType.APPLICATION_JSON_VALUE)
                    .content(request)
    )
            .andDo(print())
            .andExpect(status().isOk())
            .andReturn();

}
Run Code Online (Sandbox Code Playgroud)

当在 RequestBody 200 中使用 String 而不是 List 成功返回。我在 requestbody 中收集的错误是什么,我该如何解决?

mer*_*ksu 5

我在控制器类中使用了 @EnableWebMvc 注释并成功运行。这将激活(除其他外)REST 支持。我们需要它来注册负责序列化的 Jackson (JSON) 转换器。https://blog.zenika.com/2013/01/15/rest-web-services-testing-with-spring-mvc/中有很好的解释