spring boot单元测试之十三:用mockmvc测试文件下载(spring boot 2.4.4)

一,演示项目的相关信息:

1,地址:

https://github.com/liuhongdi/filedowntest

2,功能:演示了用mockmvc测试文件下载

3,项目结构:如图:

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,java代码说明

1,controller/HomeController.java

@RestController
@RequestMapping("/home")
public class HomeController {
    
    @GetMapping("/downexcel")
    public void downExcel(HttpServletResponse response, HttpServletRequest request) {

        try {
            //设置要下载的文件的名称
            String fileName = "商品信息.xls";
            response.setHeader("Content-Disposition",
                    "attchement;filename=" + new String(fileName.getBytes("utf-8"),
                            "ISO8859-1"));
            //通知客服文件的MIME类型
            response.setContentType("application/msexcel;charset=UTF-8");
            //获取文件的路径
            String filePath = "/data/file/html/tmb/商品信息.xls";
            FileInputStream input = new FileInputStream(filePath);
            OutputStream out = response.getOutputStream();
            byte[] b = new byte[2048];
            int len;
            while ((len = input.read(b)) != -1) {
                out.write(b, 0, len);
            }
            response.setHeader("Content-Length", String.valueOf(input.getChannel().size()));
            input.close();
        } catch (Exception ex) {
            System.out.println(ex);
        }
     }
}

2,controller/HomeControllerTest.java

@AutoConfigureMockMvc
@SpringBootTest
class HomeControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    @DisplayName("测试下载一个excel文件")
    void downExcel() throws Exception{
        mockMvc.perform(get("/home/downexcel")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED))
                .andExpect(status().isOk())
                .andDo(new ResultHandler() {
                    @Override
                    public void handle(MvcResult mvcResult) throws Exception {
                        //保存为文件
                        File file  = new File("/data/file/html/e2.xls");
                        file.delete();
                        FileOutputStream fout = new FileOutputStream(file);
                        ByteArrayInputStream bin = new ByteArrayInputStream(mvcResult.getResponse().getContentAsByteArray());
                        StreamUtils.copy(bin,fout);
                        fout.close();
                        System.out.println("is exist:"+file.exists());
                        //assert
                        System.out.println("file length:"+file.length());
                        assertThat(file.exists(), equalTo(true));
                        assertThat(file.length(), greaterThan(1024L));
                    }
                });
    }
}

三,测试效果

1,直接访问url:

http://127.0.0.1:8080/home/downexcel

开始直接下载文件:

2,运行单元测试:

四,查看spring boot版本:

  .   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _    
( ( )\___ | '_ | '_| | '_ / _` |    
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.4.4)
原文地址:https://www.cnblogs.com/architectforest/p/14610850.html