简体   繁体   中英

Spring MVC test Mulitple file upload

I have controller, which handles multiple file upload:

 @PostMapping("/import")
 public void import(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
    assertUploadFilesNotEmpty(files);
    ...
}

And I want to test it

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

Problem is that MockMvc, creates MockHttpRequest with multipartFiles as a name for param that holds uploaded files. And my controller expects those files will be in 'files' param.

Is it possible to tell spring that multiple files should be passed in request under given name?

Create two MockMultiPartFile instances with name files

Complete working example with added Json request body as well as multiple files below :

@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"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM