spring-boot - 如何使用 Spring MVC Test 对多部分 POST 请求进行单元测试?
问题描述
我正在尝试为 REST APi 创建单元测试,但在上传 excel 方法时遇到了很大问题。
这是控制器端的方法
@RestController()
@RequestMapping(path = "/upload")
@CrossOrigin(origins = "http://localhost:4200")
public class FileController {
@Autowired
FileService fileService;
@PostMapping(value = "/{managerId}/project/{projectId}")
public List<Task> importExcelFile(@RequestParam("file") MultipartFile files, @PathVariable int managerId,
@PathVariable int projectId) throws IOException, ParseException {
return fileService.getTasksFromExcel(files, managerId, projectId);
}
无论我尝试什么,我都会遇到很多错误,显然我并不真正了解我应该做什么。
我得到的主要错误是
current request is not a multipart request
解决方案
您可以执行以下操作。
我只是稍微简化了你的例子。
所以,这是一个控制器,它返回它接收到的文件的文件大小。
@RestController
@RequestMapping(path = "/upload")
public class FileController {
@PostMapping(value = "/file")
public ResponseEntity<Object> importExcelFile(@RequestParam("file") MultipartFile files) {
return ResponseEntity.ok(files.getSize());
}
}
这就是对它的考验。Spring 提供了一个名为 MockMvc 的类,可以轻松地对控制器和控制器建议进行单元测试。有一种称为multipart的方法,您可以使用它来模拟文件上传案例。
class FileControllerTest {
private final MockMvc mockMvc = MockMvcBuilders
.standaloneSetup(new FileController())
.build();
@Test
@SneakyThrows
void importExcelFile() {
final byte[] bytes = Files.readAllBytes(Paths.get("TEST_FILE_URL_HERE"));
mockMvc.perform(multipart("/upload/file")
.file("file", bytes))
.andExpect(status().isOk())
.andExpect(content().string("2037")); // size of the test input file
}
}
推荐阅读
- python - Pyspark:从 Python 到 Pyspark 实现 lambda 函数和 udf
- testing - TFS:如何将自动化测试转换为标准/手动测试
- nginx - 当用户停止查看 MP4 文件时是否可以收到通知?
- reactjs - 问:在 react js 中渲染字符串数组
- c - 为什么我的 PWM 函数可以在中断之外工作,但如果从内部调用则不能?
- c++ - 将 C 函数转换为 C++ 以检查数字是否有效
- java - 我需要能够输入一个字符串并找到特定单词的出现次数
- javascript - 通过javascript将大文件上传到服务器
- vb6 - TABCTL32.ocx 的 VB6 RegFreeCom SideBySide SxS 清单测试
- flutter - 注销提供者和共享首选项的最佳方法