I am trying to write a unit test for following component to upload file:
@Component("uploader")
public class FileUploader {
public List<FileItem> processFileUploadRequest(HttpServletRequest request) throws FileUploadException {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletContext servletContext = request.getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
ServletFileUpload upload = new ServletFileUpload(factory);
return upload.parseRequest(request);
}
}
I have written unit test using junit/mockito like following:
@Test
public void testProcessFileUploadRequestSuccess() throws FileUploadException {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
ServletContext servletContext = Mockito.mock(ServletContext.class);
Mockito.when(request.getServletContext()).thenReturn(servletContext);
Mockito.when(servletContext.getAttribute("javax.servlet.context.tempdir")).thenReturn(this.servletTmpDir);
Assert.assertNotNull(fileUploader.processFileUploadRequest(request));
}
I am getting the following error:
org.apache.commons.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is null
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:947)
...
Can anyone please give any clue regarding this? Thank you.
This error ...
the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is null
... is a result of your HttpServletRequest
not having a multipart content type.
You can fix this by adding the following line to your test case:
Mockito.when(request.getContentType()).thenReturn("multipart/form-data; boundary=someBoundary");
Ona side note: your question (specifically, this part: @Component("uploader")
) suggests that you are using Spring. If so, then perhaps your file upload code could be more easily tested using Spring's MockMvcRequestBuilders#fileUpload(String, Object...)
to return a MockMultipartHttpServletRequestBuilder
. Something like this:
mockMvc.perform(MockMvcRequestBuilders.fileUpload("/upload")
.file(aFile)
.andExpect(status().is(200))
.andExpect(content().string("..."));
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.