简体   繁体   中英

Test file upload Spring MVC

I would like to test file uploading by REST API. I found it quite confusing to send file as RequestParam instead of RequestBody .

Controller method:

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public
@ResponseBody
ResponseEntity<String> uploadFile(
        @RequestParam(name = "file") MultipartFile multipartFile,
        @RequestParam(name = "path") String path) {
    logger.debug("File upload REST requested");

    return new ResponseEntity<>(fileService.uploadFile(
            multipartFile, path),
            HttpStatus.OK);
}

1.Now I would like to test it and I've used mocks. While debugging it, I see that mock service working but method exactly with this arguments is not invoked, so the test if failed. How could I handle this?

@Test
public void testUploadFile() throws Exception {
    String mockName = "mock";
    MockMultipartFile mockMultipartFile = new MockMultipartFile(mockName, mockName.getBytes());

    when(mockFileService.uploadFile(mockMultipartFile, rootDir)).thenReturn("success");

    mockMvc.perform(MockMvcRequestBuilders.fileUpload("/files/upload")
            .file("file", mockMultipartFile.getBytes())
            .param("path", rootDir))
            .andExpect(status().isOk())
            .andExpect(content().string("success"));

    verify(mockFileService, times(1)).updateFile(mockMultipartFile, rootDir);
    verifyNoMoreInteractions(mockFileService);
}

2.How could I test this with Postman? I see that I can send file in Body, but how could I send it as param?

EDIT:

I've changed the method, but the problem is not there:

Argument(s) are different! Wanted:
mockFileService.uploadFile(
org.springframework.mock.web.MockMultipartFile@61bd0845,
"/"
);

Looks like method are using 2 instances of MockMultipartFile. And the second question is still open, how could this method be tested from Postman?

Yes, the test case fails, because the problem is in your test case at the end, you are verifying the call to updateFile () which is incorrect as in your controller you are using uploadFile (), you MUST use the same method to verify .

So, you need to change the verify line as below:

verify(mockFileService, times(1)). uploadFile(mockMultipartFile, rootDir);

In other words, Mockito verify validates the number of times a method is invoked as you are trying to verify the call on a different method (not being used in controller), it is failing.

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