我有控制器,可以处理多个文件上传:
@PostMapping("/import")
public void import(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
assertUploadFilesNotEmpty(files);
...
}
我想测试它
@Test
public void importTest() throws Exception {
MockMultipartFile file = new MockMultipartFile("file", "list.xlsx", MIME_TYPE_EXCEL, Files.readAllBytes(Paths.get(excelFile.getURI())));
mvc.perform(fileUpload("/import").file(file).contentType(MIME_TYPE_EXCEL)).andExpect(status().isOk());
}
问题是MockMvc使用multipartFiles创建MockHttpRequest作为保存上传文件的param的名称。而我的控制器希望这些文件可以放在'文件中。 PARAM。
是否有可能告诉spring应该在给定名称下的请求中传递多个文件?
答案 0 :(得分:3)
创建名为MockMultiPartFile
files
个实例
完整的工作示例,添加了Json请求正文以及下面的多个文件:
@PostMapping(consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
public void addProduct(@RequestPart(value="addProductRequest") @Valid AddUpdateProductRequest request,
@RequestPart(value = "files") final List<MultipartFile> files) throws Exception{
request.setProductImages(files);
productService.createProduct(request);
}
@Test
public void testUpdateProduct() throws Exception {
AddUpdateProductRequest addProductRequest = prepareAddUpdateRequest();
final InputStream inputStreamFirstImage = Thread.currentThread().getContextClassLoader().getResourceAsStream("test_image.png");
final InputStream inputStreamSecondImage = Thread.currentThread().getContextClassLoader().getResourceAsStream("test_image2.png");
MockMultipartFile jsonBody = new MockMultipartFile("addProductRequest", "", "application/json", JsonUtils.toJson(addProductRequest).getBytes());
MockMultipartFile file1 = new MockMultipartFile("files", "test_image.png", "image/png", inputStreamFirstImage);
MockMultipartFile file2 = new MockMultipartFile("files", "test_image2.png", "image/png", inputStreamSecondImage);
ResultMatcher ok = MockMvcResultMatchers.status().isOk();
mockMvc.perform(MockMvcRequestBuilders.fileUpload("/add-product")
.file(file1)
.file(file2)
.file(jsonBody)
.contentType(MediaType.MULTIPART_FORM_DATA_VALUE))
.andDo(MockMvcResultHandlers.log())
.andExpect(ok)
.andExpect(content().string("success"));
}