java spring boot test内容中包含对象的POST REST

时间:2017-11-27 10:17:37

标签: java spring-boot junit

我尝试对邮政休息服务进行单元测试,此服务将对象(不是json)作为内容。结果是我无法测试它,MockMvc对象需要一些json内容。

控制器的一部分,其中Dsd是应用程序的内部类:

@PostMapping(path="dsd")
@ApiOperation(value = "Sends Dsd  data",response = Dsd.class)
public Dsd requestPostDsd (
        @ApiParam("DSD data")
        @Valid @RequestBody Dsd dsd,
        HttpServletResponse response
) throws IOException, ParseException {
    if (dsd.getId() != null) {
        // do something
    } else {
        response.sendError(HttpStatus.BAD_REQUEST.value(), "the id doesn't exist");
    }
    return dsd;
}

在单元测试代码中,我创建了一个MockMvc对象,但是perform()。content方法需要一个字符串json内容,我不能通过我的Dsd对象。

如何测试此POST api?

编辑:部分测试代码:

 @Test
public void postDsdTest() throws Exception {

    Dsd dsd = new Dsd();

    this.mvc.perform(post("/services/latest/validation/dsd")
            .header("Origin", HTTP_HEADER_ORIGIN)
            .header("Accept", "application/json")
            .content(dsd)
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(header().string("Access-Control-Allow-Origin", HTTP_HEADER_ORIGIN))
            .andExpect(status().isOk())
            .andDo(MockMvcResultHandlers.print());

}

1 个答案:

答案 0 :(得分:0)

您可以尝试编写一个TestUtil类,将对象序列化为JSON字符串:https://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-mvc-controllers-rest-api/

使用Jackson,您可以将对象序列化为JSON:

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsBytes(object);