springBoot中使用使用junit測試文件上傳,以及文件下載接口編寫


本篇文章將介紹如何使junit在springBoot中測試文件的上傳,首先先閱讀如何在springBoot中進行接口測試.

文件上傳操作測試代碼

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

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

  @Test
  public void contextLoads() {
  }

  @Autowired
  private WebApplicationContext wac;

  private MockMvc mockMvc;

  /** * 在每次測試執行前構建mvc環境 */
  @Before
  public void setup() {
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
  }
  /** * 測試上傳文件 */
  @Test
  public void whenUploadFileSuccess() {
    try {
     String result =  mockMvc.perform(
          MockMvcRequestBuilders
              .fileUpload("/file")
              .file(
                  new MockMultipartFile("file", "test.txt", ",multipart/form-data", "hello upload".getBytes("UTF-8"))
              )
      ).andExpect(MockMvcResultMatchers.status().isOk())
      .andReturn().getResponse().getContentAsString();
      System.out.println(result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

   
   
   
           

 編寫文件下載接口

package com.micro.fast.security.demo.controller;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/file")
public class FileController {
  /** * 處理文件上傳 * @param file */
  @PostMapping
  public  String  upload(MultipartFile file){
    File localfile = new File("/file/name");
    try {
      //將文件上傳到本地路徑
      file.transferTo(localfile);
    } catch (IOException e) {
      e.printStackTrace();
    }
    String fileInfo = "";
    fileInfo += file.getName()+file.getOriginalFilename()+file.getContentType();
    return fileInfo;
  }

  /** * 文件的下載 * @param id * @param request * @param response */
  @GetMapping("/{id}")
  public void download(@PathVariable String id , HttpServletRequest request, HttpServletResponse response){
    try (InputStream inputStream = new FileInputStream(new File("/root/file/name"));
         OutputStream outputStream = response.getOutputStream();
    ){
      response.setContentType("application/x-download");
      //指定文件的名稱
      response.addHeader("Content-Disposition","attachment;filename=test.txt");
      IOUtils.copy(inputStream,outputStream);
      outputStream.flush();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

   
   
   
           

原文地址:https://blog.csdn.net/c_intmian/article/details/79543292


免責聲明!

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



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