【问题标题】:MockHttpServletResponse has empty in test, despite Controller working correctly尽管控制器正常工作,但 MockHttpServletResponse 在测试中为空
【发布时间】:2021-11-03 09:42:01
【问题描述】:

我正在使用MockMvc 测试@RestController POST 端点。 在此测试中,MockHttpServletResponse 内容始终为空且未设置内容类型。 我检查了控制器方法;它被调用并返回正确的响应。 在测试中,状态码被正确设置为 201。

这是测试:

@Test
public void testBookCreation() throws Exception {
    var response = mockMvc.perform(
        MockMvcRequestBuilders
            .post("/books/create")
            .contentType(MediaType.APPLICATION_JSON)
            .content(
                jsonb.toJson(new Book("KR","K & R",5,8))
            )
    ).andExpect(
        MockMvcResultMatchers.status().isCreated()
    ).andExpect(
        MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)
    ).andExpect(
        MockMvcResultMatchers.jsonPath("$.author").exists()
    ).andDo((result)->{
        System.out.println(result.getResolvedException());
        System.out.println(result.getResponse());
    }).andReturn();
    }

这是控制器方法:

@PostMapping("/create")
@ResponseStatus(code=HttpStatus.CREATED,reason="Book created")
public Book makeBook(@RequestBody Book b ) {
    var res = bookRepository.save(b);
    System.out.println(res);
    return res;
}

我认为问题出在测试而不是控制器本身。

【问题讨论】:

    标签: java spring-boot spring-mvc spring-mvc-test


    【解决方案1】:

    ResponseStatus 的文档说明如下:

    警告:在异常类上使用该注解,或设置该注解的原因属性时,将使用HttpServletResponse.sendError方法。

    意味着您将收到以下形状的响应,无论您的控制器中发送的有效负载是什么响应

    {
      "timestamp":"",
      "status":201,
      "error":"Created",
      "message":"",
      "path":"/books/create"
    }
    

    然后您应该删除 ReponseStatus 注释的 reason 字段:

    @PostMapping("/create")
    @ResponseStatus(code=HttpStatus.CREATED)
    public Book makeBook(@RequestBody Book b ) {
        var res = bookRepository.save(b);
        System.out.println(res);
        return res;
    }
    

    【讨论】:

    • 很高兴能得到帮助。
    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多