0

我正在尝试编写一个单元测试,检查用户是否可以从 syte 下载 PDF 文件。我使用版本 2.1.2.RELEASE 的 spring-boot-starter-parent。

控制器中的方法:

    @GetMapping(value = "/download", produces = MediaType.APPLICATION_PDF_VALUE)
    @ResponseBody
    public ResponseEntity<Resource> downloadFile() {
        Resource resource = ...;
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
            "attachment; filename=\"" + resource.getFilename() + '"').body(resource);
    }

测试方法:

    @Test
    public void shouldFail() throws Exception {
        byte[] anyBytes = new byte[]{};
        mockMvc.perform(get("/download"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_PDF_VALUE))
            .andExpect(content().bytes(anyBytes));
    }

在控制器方法中,我提供现有的 PDF 文件作为资源。接下来在测试中,我将响应正文与一个肯定不等于我的 PDF 资源的字节数组进行比较。所以测试预计会失败。但它通过了。

经过一些研究,我发现无论向 content().bytes() 提供什么字节数组 - 测试都通过了。有趣的是,bytes() 方法在里面抛出了 AssertionError,但不知何故被吞噬了。

这是一个错误还是我做错了什么?

4

0 回答 0