【问题标题】:Spring Boot REST Controller Integration Test returns 406 instead of 500Spring Boot REST 控制器集成测试返回 406 而不是 500
【发布时间】:2020-05-19 13:07:21
【问题描述】:

我有一个带有端点的控制器,它产生压缩数据的字节流。下面代码中的MyDtOZipService 类是自定义类,它们充当POJO,我想将其内容添加到zip 和一个服务,它将获取POJO 的字节并将它们写入ZipOutputStream 哪个然后将通过包装在带有适当HttpStatus 和标头的ResponseEntity 对象中的端点提供。 “快乐路径”运行良好,并按预期生成 zip 文件。

@GetMapping(path = "/{id}/export", produces = "application/zip")
public ResponseEntity<byte[]> export(@ApiParam(required = true) @PathVariable(value = "id") String id) throws IOException {
    try {
        MyDTO myDTO = myService.getDTO(id);
        byte[] zippedData = zipService.createZip(myDTO.getBytes());
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""name.zip\"");
        return new ResponseEntity<>(zipDTO.getData(), httpHeaders, HttpStatus.OK);
    } catch (ZipException e) {
        return new ResponseEntity(e.getRestError(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

当我想测试抛出自定义ZipException 的情况时,问题出在我的集成测试类中(如果压缩的数据出现问题,可能会发生这种情况)。在我们的组织中,我们必须遵守的标准之一是每个自定义异常都需要扩展 Exception 并具有一个名为 RestError 的自定义对象,该对象具有表示自定义错误代码和消息的字符串变量。

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class RestError {

    private String code;
    private String message;

    //Constructors

    //Getters and setters
}

这个对象似乎会导致集成测试出现问题

@Test
public void myIntegrationTest() throws Exception {
    MyDTO myDTO = new MyDTO();
    RestError restError = new RestError("Custom error code", "Custom error message")
    ZipException zipException = new ZipException(restError);
    given(myService.getDTO("id")).willReturn(myDTO);
    given(zipService.createZip(any(), any())).willThrow(zipException);

    mockMvc.perform(get("/{id}/export", "id").accept(MediaType.ALL)
            .andDo(print())
            .andExpect(status().is5xxServerError());
}

在这种情况下,我希望 HttpStatus 达到 500,但 MockMvc 达到 406 的 HttpStatus - 内容不可接受。我已经搞砸了测试,以便它可以接受并期待任何/所有数据,但它仍然每次都会遇到 406 错误。我知道这与异常的 RestError 对象有关,因为如果我将其从控制器返回的 ResponseEntity 中取出,则返回预期的响应状态。对此的任何帮助表示赞赏。

【问题讨论】:

    标签: java spring-boot integration-testing


    【解决方案1】:

    @GetMapping(path = "/{id}/export", produces = "application/zip") 中删除产品 并将其更改为@GetMapping(path = "/{id}/export")

    因此在测试用例执行期间返回 406 错误 如果你删除它,你会得到你抛出的确切错误。

    但是请检查 zip 文件是否按预期下载。

    【讨论】:

    • 谢谢,这很有效,我的端点仍在正确下载 zip。但是为什么注释的“产生”部分会导致这个问题?
    猜你喜欢
    • 2018-04-27
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2017-06-05
    • 2018-06-23
    相关资源
    最近更新 更多