Search code examples
springapachefileuploadmockmvc

How to mock a multipart file upload when using Spring and Apache File Upload


The project I'm working on needs to support large file uploads and know the time taken during their upload.

To handle the large files I'm using the streaming API of Apache FileUpload, this also allows me to measure the time taken for the complete stream to be saved.

The problem I'm having is that I cannot seem to be able to utilise MockMvc in an Integration Test on this controller. I know that the controller works as I've successfully uploaded files using postman.

Simplified Controller Code:

@PostMapping("/upload")
public String handleUpload(HttpServletRequest request) throws Exception {
    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iterStream = upload.getItemIterator(request);
    while (iterStream.hasNext()) {
        FileItemStream item = iterStream.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (!item.isFormField()) {
            // Process the InputStream
        } else {
            String formFieldValue = Streams.asString(stream);
        }
    }
}

Simplified Test Code:

private fun uploadFile(tfr: TestFileContainer) {
    val mockFile = MockMultipartFile("file", tfr.getData()) // .getData*() returns a ByteArray


    val receiveFileRequest = MockMvcRequestBuilders.multipart("/upload")
    .file(mockFile)
    .contentType(MediaType.MULTIPART_FORM_DATA)

    val result = mockMvc.perform(receiveFileRequest)
      .andExpect(status().isCreated)
      .andExpect(header().exists(LOCATION))
      .andReturn(

}

This is the error I'm currently getting

org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

Can anyone help?


Solution

  • The MockMultipartFile approach won't work as Spring does work behind the scenes and simply passes the file around.

    Ended up using RestTemplate instead as it actually constructs requests.