'How to mock file payloads in HttpServletRequest without a framework?

I've written a servlet to upload files to the server via HttpServletRequest and I need to test it. Unfortunately the framework at work isn't allowing mocking frameworks, so I need to write my own mock of HttpServletRequest for JUnit tests.

I'm using some Apache Commons classes we have available to get files from the request:

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

private static List<FileItem> getFilesFromReq(final HttpServletRequest request) {
    final FileItemFactory factory = new DiskFileItemFactory();
    final ServletFileUpload upload = new ServletFileUpload(factory);

    List<FileItem> fileItems = new ArrayList<>();
    try {
        fileItems = upload.parseRequest(request);
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
    return fileItems;
}

I've written an implementation of HttpServletRequest as the mock (actually an extension of a partial mock someone else in the company wrote). But I can't figure out how to add to the request body, let alone how to include files as multipart/form-data. And there don't seem to be any methods in HttpServletRequest even referencing the request body.

I found online the source code of DiskFileItemFactory/FileItemFactory and ServletFileUpload, but how it works and how the files are included in the request is still rather opaque to me.

Can anyone give me some guidance for adding files to multipart/form-data in a mock HttpServletRequest?



Solution 1:[1]

I would recommend making this method non-static first of all. Next, instead of instantiating the ServletFileUpload instance in the method it should be injected in the constructor of your class.

class FileUploader { 
private final ServletFileUpload servletFileUpload;

FileUploader(ServletFileUpload servletFileUpload) {
  this.servletFileUpload = servletFileUpload;
}

}

Now in your test you can pass in a mock of ServletFileUpload. You can use Mockito or JMock or create your own mock class. After doing this you'll be able to verify that the your mocked class's method parseRequest was called.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Steven Diamante