我正在尝试为 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
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句