单元测试上传文件

package com.zfq.springcloud.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("/upload")
public String upload(@RequestPart(name = "file") MultipartFile file){
File localfile = new File("D:/file/name/1.jpg");
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();
}
}
}








package com.zfq.springcloud.controller;

import org.junit.Before;
import org.junit.jupiter.api.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.ResultActions;
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.io.File;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;

import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

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

@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();
}
}*/

@Test
public void uploadFile() throws Exception {
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();

String filePath = this.getClass().getResource("/1.jpg").getPath();
File file = new File(filePath);
MockMultipartFile mockMultipartFile = new MockMultipartFile("file", //文件名
file.getName(), //originalName 相当于上传文件在客户机上的文件名
MediaType.IMAGE_JPEG_VALUE, //文件类型
new FileInputStream(file) //文件流
);
ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.multipart("/file/upload").file(mockMultipartFile));
String contentAsString =
resultActions.andExpect(MockMvcResultMatchers.status().isOk()).andReturn().getResponse()
.getContentAsString();
System.out.println(contentAsString);
resultActions.andDo(print());

//String filePath = this.getClass().getResource("D:\\Hzero\\cloud2020\\cloud-consumer-order80\\src\\test\\resource\\1.jpg").getPath();
/* File file = new File("D:\\Hzero\\cloud2020\\cloud-consumer-order80\\src\\test\\resource\\1.jpg");
MockMultipartFile firstFile = new MockMultipartFile("file", "2.xlsx",
MediaType.IMAGE_JPEG_VALUE, new FileInputStream(file));
mockMvc.perform(MockMvcRequestBuilders.multipart("/file/upload").file(firstFile)
.contentType(MediaType.MULTIPART_FORM_DATA_VALUE))
.andExpect(MockMvcResultMatchers.status().isOk()).andDo(print());
}*/
}
}



posted @ 2021-02-05 01:06  奥里给  阅读(752)  评论(0编辑  收藏  举报