【发布时间】:2020-05-19 13:07:21
【问题描述】:
我有一个带有端点的控制器,它产生压缩数据的字节流。下面代码中的MyDtO 和ZipService 类是自定义类,它们充当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