Close

Spring MVC - Testing Multipart uploads with MockMultipartFile

[Last Updated: Feb 1, 2018]

This example shows how to unit test Spring File upload controller by using MockMultipartFile.

MockMultipartFile does not use the application registered MultipartResolver, that means it is only suitable for testing application controllers that access multipart uploads.

Example

The Controller

@Controller
@RequestMapping("/upload")
public class FileUploadController {
  public static final String targetFolder=  "d:/filesUploaded/";

  @RequestMapping(method = RequestMethod.POST)
  @ResponseBody
  public String handlePostRequest(MultipartHttpServletRequest request,
                                  Model model) throws IOException {

      MultipartFile multipartFile = request.getFile("user-file");
      String name = multipartFile.getOriginalFilename();
      InputStream inputStream = multipartFile.getInputStream();

      Files.copy(inputStream, Paths.get(targetFolder + name), StandardCopyOption.REPLACE_EXISTING);
      model.addAttribute("msg", "File has been uploaded:  " + name);
      return "test response body";
  }
}

Java Config

@EnableWebMvc
@Configuration
public class MyWebConfig {

  @Bean
  public FileUploadController uploadController() {
      return new FileUploadController();
  }
}

The Test class

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyWebConfig.class)
public class UploadControllerTest {

  @Autowired
  private WebApplicationContext wac;
  private MockMvc mockMvc;

  @Before
  public void setup() {
      DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
      this.mockMvc = builder.build();
  }

  @Test
  public void testController() throws Exception {
      ResultMatcher ok = MockMvcResultMatchers.status().isOk();

      String fileName = "test.txt";
      File file = new File(FileUploadController.targetFolder + fileName);
      //delete if exits
      file.delete();

      MockMultipartFile mockMultipartFile = new MockMultipartFile("user-file",fileName,
              "text/plain", "test data".getBytes());

      MockHttpServletRequestBuilder builder =
              MockMvcRequestBuilders.fileUpload("/upload")
                                    .file(mockMultipartFile);
      this.mockMvc.perform(builder).andExpect(ok)
                  .andDo(MockMvcResultHandlers.print());;
      Assert.assertTrue(file.exists());
  }
}
mvn test -q

Output

d:\example-projects\spring-mvc\file-upload\spring-mock-multipart-file-example>mvn test -q

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.UploadControllerTest

MockHttpServletRequest:
HTTP Method = POST
Request URI = /upload
Parameters = {}
Headers = {Content-Type=[multipart/form-data]}

Handler:
Type = com.logicbig.example.FileUploadController
Method = public java.lang.String com.logicbig.example.FileUploadController.handlePostRequest(org.springframework.web.multipart.MultipartHttpServletRequest,org.springframework.ui.Model) throws java.io.IOException

Async:
Async started = false
Async result = null

Resolved Exception:
Type = null

ModelAndView:
View name = null
View = null
Model = null

FlashMap:
Attributes = null

MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[text/plain;charset=ISO-8859-1], Content-Length=[18]}
Content type = text/plain;charset=ISO-8859-1
Body = test response body
Forwarded URL = null
Redirected URL = null
Cookies = []
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.108 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

Note:

Starting Spring 5.0, MockMvcRequestBuilders.fileUpload has been deprecated in favor of MockMvcRequestBuilders.multipart() method. Check out this example.

Example Project

Dependencies and Technologies Used:

  • spring-webmvc 4.2.4.RELEASE: Spring Web MVC.
  • spring-test 4.2.4.RELEASE: Spring TestContext Framework.
  • javax.servlet-api 3.0.1 Java Servlet API
  • junit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • commons-fileupload 1.3.1: The Apache Commons FileUpload component provides a simple yet flexible means of adding support for multipart file upload functionality to servlets and web applications.
  • JDK 1.8
  • Maven 3.3.9

Spring File Upload Unit Test Example Select All Download
  • spring-mock-multipart-file-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MyWebConfig.java
        • test
          • java
            • com
              • logicbig
                • example

    See Also