How to create CommonsMultipartFile object given only a file

wsams picture wsams · Apr 29, 2010 · Viewed 33.2k times · Source

I have a junit test method that takes a CommonsMultipartFile object as a parameter.

I'm trying to create a FileItem object so I can pass it to the constructor,

CommonsMultipartFile(org.apache.commons.fileupload.FileItem fileItem)

To do that, I'm trying to create the FileItem object using the DiskFileItem constructor,

DiskFileItem(java.lang.String fieldName, java.lang.String contentType, boolean isFormField, java.lang.String fileName, int sizeThreshold, java.io.File repository)

but I'm not sure how to pass any of those parameters.

I have all of this working in a Spring 3 MVC controller, but to do my junit tests, I need to pass a method two objects. One is the UploadItem object which looks like the following,

import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class UploadItem {
 private String fileName;
 private String filePath;
 private CommonsMultipartFile fileData;

 public String getFileName() {
  return fileName;
 }

 public void setFileName(String fileName) {
  this.fileName = fileName;
 }

 public String getFilePath() {
  return filePath;
 }

 public void setFilePath(String filePath) {
  this.filePath = filePath;
 }

 public CommonsMultipartFile getFileData() {
  return fileData;
 }

 public void setFileData(CommonsMultipartFile fileData) {
  this.fileData = fileData;
 }
}

The setFileData() method requires the CommonsMultipartFile object which I'm trying to create just given a file in my src/test/resources directory.

Would anyone know how I can take a file, create a FileItem object and pass that to the CommonsMultipartFile object constructor?

Thanks. If anything is unclear, please let me know - I'm not that familiar with Spring MVC file uploads.

Answer

Ralph picture Ralph · Jul 26, 2011

Use the more common interface org.springframework.web.multipart.MultipartFile. instead of org.springframework.web.multipart.commons.CommonsMultipartFile in your Command (UploadItem). (CommonsMultipartFile is a 1:1 implementation of the Interface).

Now you can create an instance of CommonsMultipartFile with the mock class org.springframework.mock.web.MockMultipartFile. (which is element of spring-test.jar).

Then the creation of an MultipartFile in the tests is only one statement, without any cast:

MockMultipartFile mockMultipartFile = new MockMultipartFile(
       "test.txt",                //filename
       "Hallo World".getBytes()); //content