contentType "application/octet-stream" 的 mockmvc 下载功能抛出 FileNotFound 错误

mockmvc download functionality for contentType "application/octet-stream" throws FileNotFound error

我是 mockmvc 的新手 api。

我正在尝试为我的控制器编写单元,其中一种方法执行下载。请找到代码片段:

控制器:

@RequestMapping(value = "/download-template", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    @ResponseBody
    public FileSystemResource downloadTemplate(HttpServletRequest request,
            HttpServletResponse response) {

        logger.info("User ID: " + request.getAttribute("userId")
                + " - POST: /upload/download-template");

        String rootDir = config.getBaseFolder();
        DownloadUploadTemplateResponse res = uploadService.downloadTemplate(
                rootDir, false);

        response.setHeader("Content-Disposition",
                "attachment; filename=" + res.getFileName());

        return new FileSystemResource(res.getTemplateFile());

    }

单元测试代码:

@Test
    public void testDownloadTemplate(){
        DownloadResponse res = new DownloadResponse();
        String templateFile = "upload-template.xlsx";
        String fileName = System.getProperty("java.io.tmpdir") + templateFile;
        res.setFileName(fileName);
        res.setTemplateFile(templateFile);
        when(config.getBaseFolder()).thenReturn(System.getProperty("java.io.tmpdir"));
        when(uploadService.downloadTemplate( System.getProperty("java.io.tmpdir"), false)).thenReturn(res);
        //File file = new File(fileName);
        FileSystemResource resource = new FileSystemResource(res.getTemplateFile());
        try{
            ResultActions action = mockMvc.perform(get("/upload/download-template").contentType(APP_OCTET_STREAM_VALUE_UTF8));
            action.andExpect(header().string("Content-Disposition",
                    "attachment; filename=" + res.getFileName()));
            action.andExpect(status().isOk());


        }catch(Exception e){
            e.printStackTrace();
            fail();
        }
    }

下面一行抛出java.io.FileNotFoundException: upload-template.xlsx(系统找不到指定的文件): ResultActions 动作 = mockMvc.perform(get("/upload/download-template").contentType(APP_OCTET_STREAM_VALUE_UTF8));

请指导我需要在 httprequestbuilder 中添加哪些额外内容来解决此问题。

我的错 .. 错误很明显,可以解决问题。问题是文件实际上并不存在 :)。 因此,将文件放在临时文件夹中可以帮助我解决问题。感觉像啊。