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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM