Close

Spring MVC - MockMvcRequestBuilders.fileUpload() Example

This example, shows how to use MockMvcRequestBuilders.fileupload().

Note that, starting Spring 5.0, MockMvcRequestBuilders.fileUpload() has been deprecated in favor of MockMvcRequestBuilders.multipart() method.

@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

Output

D:\example-projects\spring-mvc\file-upload\spring-mock-mvc-request-builders-multipart>mvn test
[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for com.logicbig.example:spring-mock-mvc-request-builders-multipart:war:1.0-SNAPSHOT
[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-war-plugin is missing. @ line 42, column 21
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] --< com.logicbig.example:spring-mock-mvc-request-builders-multipart >---
[INFO] Building spring-mock-mvc-request-builders-multipart 1.0-SNAPSHOT
[INFO] from pom.xml
[INFO] --------------------------------[ war ]---------------------------------
[INFO]
[INFO] --- resources:3.3.1:resources (default-resources) @ spring-mock-mvc-request-builders-multipart ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\example-projects\spring-mvc\file-upload\spring-mock-mvc-request-builders-multipart\src\main\resources
[INFO]
[INFO] --- compiler:3.5.1:compile (default-compile) @ spring-mock-mvc-request-builders-multipart ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- resources:3.3.1:testResources (default-testResources) @ spring-mock-mvc-request-builders-multipart ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\example-projects\spring-mvc\file-upload\spring-mock-mvc-request-builders-multipart\src\test\resources
[INFO]
[INFO] --- compiler:3.5.1:testCompile (default-testCompile) @ spring-mock-mvc-request-builders-multipart ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- surefire:3.2.5:test (default-test) @ spring-mock-mvc-request-builders-multipart ---
[INFO] Using auto detected provider org.apache.maven.surefire.junit4.JUnit4Provider
[WARNING] file.encoding cannot be set as system property, use <argLine>-Dfile.encoding=...</argLine> instead
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] 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

Async:
Was async started = false
Async result = null

Resolved Exception:
Type = null

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

FlashMap:

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 = []
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.524 s -- in com.logicbig.example.UploadControllerTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.175 s
[INFO] Finished at: 2026-06-07T15:43:20+08:00
[INFO] ------------------------------------------------------------------------

Example Project

Dependencies and Technologies Used:

  • spring-webmvc 4.0.0.RELEASE (Spring Web MVC)
  • spring-test 4.0.0.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.9.11

spring-mock-mvc-request-builders-multipart Select All Download
  • spring-mock-mvc-request-builders-multipart
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • FileUploadController.java
        • test
          • java
            • com
              • logicbig
                • example

    See Also

    Join