Reputation: 619
I am currently trying to test some code I have in a web application that takes a HTTP multipart/form request and converts it into a list of FileItems I can use later on. Here is the method:
private HttpServletRequest request = null;
private List<FileItem> uploadedObjects = null;
/* getter/setter methods */
public void upload() throws FileUploadException {
ServletFileUpload upload = new ServletFileUpload(
new DiskFileItemFactory());
if (request == null) {
//do nothing - success is already false
} else if (ServletFileUpload.isMultipartContent(request)) {
uploadedObjects = upload.parseRequest(request);
success = true
}
}
The problem is that I'm having trouble unit testing this method. I've tried to use EasyMock to mock a HttpServletRequest, but in order to mock a ServletInputStream's read method you basically have to re-implement read() -- there has to be an easier way.
I tried using commons-httpclient 3.0 to create a multipart request, which worked in that I successfully created a MultipartRequestEntity, but I'm not sure how to use that in upload() since it involves two different object types. Is it possible? What steps can I take to successfully simulate a request object?
Upvotes: 1
Views: 1775
Reputation: 136
It looks like your problem is the fact that ServletFileUpload is being constructed and used within the method, as that class is inherent dependency not within this class. I'd suggest overloading the upload method in order to remove the ServletFileUpload dependency:
public void upload() throws FileUploadException {
ServletFileUpload servletUpload = new ServletFileUpload(new DiskFileItemFactory());
upload(servletUpload);
}
public void upload(ServletFileUpload servletUpload) throws FileUploadException{
if (request == null) {
//do nothing - success is already false
} else if (ServletFileUpload.isMultipartContent(request)) {
uploadedObjects = servletUpload.parseRequest(request);
success = true
}
}
Then, use EasyMock to generate a mock of the ServletFileUpload with an expected call to parseRequest that returns a list of type FileItem. Use that mock in a unit test against the upload(ServletFileUpload servletUpload) method.
Upvotes: 1