文档章节

Spring Boot Controller单元测试

o
 osc_bkdv2it5
发布于 2019/08/19 14:39
字数 344
阅读 14
收藏 0

一、创建Controller

一个方法是用传统IO来下载文件,一个是NIO下载文件

@Controller
public class FileController {

    private Logger log = LoggerFactory.getLogger(FileController.class);


    @RequestMapping(value="/download/oldio}", method = RequestMethod.GET)
    public void download(HttpServletRequest request, HttpServletResponse response,String fileName) throws IOException{
         String folder = "C://Users/xxx/Downloads/0714";
         File file = new File(folder, fileName);
         if(file.exists()){
             response.setContentType("MimeType");
             response.addHeader("Content-Disposition","attachment;filename=" +fileName);
             response.setContentLength((int)file.length());

             //Java IO
             InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
             //Copy bytes from source to destination(outputstream in this example), closes both streams.
             FileCopyUtils.copy(inputStream, response.getOutputStream());

             log.info("download success! ---" + fileName);



         }else {
             throw  new Error("file not exist");
         }
     }


    @RequestMapping(value="/download/nio}", method = RequestMethod.GET)
    public void downloadfornio(HttpServletRequest request, HttpServletResponse response, String fileName) throws IOException{
        String folder = "C://Users/xxx/Downloads/0714";
        File file = new File(folder, fileName);
        if(file.exists()){
            response.setContentType("MimeType");
            response.addHeader("Content-Disposition","attachment;filename=" +fileName);
            response.setContentLength((int)file.length());

            //128 * 1024 = 128K
            int bufferSize = 131072 * 6;
            FileInputStream fileInputStream = new FileInputStream(file);
            FileChannel fileChannel = fileInputStream.getChannel();
            // 6 * 128K = 768K = 786432
            ByteBuffer buffer = ByteBuffer.allocateDirect(786432);
            byte[] byteArr = new byte[bufferSize];
            int nRead, nGet;

            try {
                while ((nRead = fileChannel.read(buffer)) != -1){
                    if(nRead == 0){
                        continue;
                    }
                    buffer.position(0);
                    buffer.limit(nRead);
                    while (buffer.hasRemaining()){
                        nGet = Math.min(buffer.remaining(), bufferSize);
                        // read bytes from disk
                        buffer.get(byteArr,0,nGet);
                        //write bytes to output
                        response.getOutputStream().write(byteArr);
                    }
                    buffer.clear();


                }
                log.info("download success! ---" + fileName);
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                buffer.clear();
                fileChannel.close();
                fileInputStream.close();
            }



        }else {
            throw  new Error("file not exist");
        }
    }
}

  

二、创建单元测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class FileControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;

    private  FileController fc;

    @Before
    public  void  setup(){
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
        fc = this.wac.getBean(FileController.class);
    }



    @Test
    public void compareTime() throws Exception {

        String fileName = "11.tar.gz";
        MockHttpServletRequest request = new MockHttpServletRequest();
        MockHttpServletResponse response = new MockHttpServletResponse();


        long c = System.currentTimeMillis();
        fc.downloadfornio(request, response, fileName);
        long d = System.currentTimeMillis();
        System.out.println("nio download takes :" + (d - c) );

        long a = System.currentTimeMillis();
        fc.download(request, response,fileName);
        long b = System.currentTimeMillis();
        System.out.println("io download takes :" + (b - a) );




    }

}

  输出结果

nio download takes :144
io download takes :164

  

o
粉丝 0
博文 500
码字总数 0
作品 0
私信 提问
加载中
请先登录后再评论。

暂无文章

OSChina 周五乱弹 —— 你大妈还是你大妈

Osc乱弹歌单(2020)请戳(这里) 【今日歌曲】 @watergood:是时候分享一波我的这张纯音乐歌单了,过去的五年多时间里,我陆陆续续地把听到的好听的纯音乐添加了进去,目前一共65首,相信总...

小小编辑
今天
19
0
在Objective-C中生成随机数 - Generating random numbers in Objective-C

问题: I'm a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method: 我主要是Java头,我想要一种生成0到74之间的伪随......

技术盛宴
今天
13
0
ftp-ftps-sftp的关系

Ftp FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为“文传协议”。用于Internet上的控制文件的双向传输。同时,它也是一个应用程序(Application)。基于不同的操作...

独钓渔
今天
12
0
使Vim将所有空格显示为字符 - Make Vim show ALL white spaces as a character

问题: I can't find a way to make Vim show all white spaces as a character. 我找不到让Vim将所有空白显示为字符的方法。 All I found was about tabs, trailing spaces etc. 我发现的只......

富含淀粉
今天
23
0
RN 接入高德地图遇到的一些问题

react-native-amap-geolocation、react-native-amap3d 1、iOS Geolocation.getCurrentPosition 获取坐标后,没有返回 address 信息? 逆地理编码 Android 默认返回逆地理编码,而 iOS 需要手...

Jack088
今天
14
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部