Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:


1. Overview

In this quick tutorial, we’re going to see how to test a multipart POST request in Spring using MockMvc.

2. Maven Dependencies

Before we begin, let’s add the latest JUnit and Spring test dependencies in our pom.xml:


3. Testing a Multipart POST Request

Let’s create a simple endpoint in our REST controller:

@PostMapping(path = "/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
    return file.isEmpty() ?
      new ResponseEntity<String>(HttpStatus.NOT_FOUND) : new ResponseEntity<String>(HttpStatus.OK);

Here, the uploadFile method accepts a multipart POST request. In this method, we’re sending status code 200 if the file exists; otherwise, we’re sending status code 404.

Now, let’s test the above method using MockMvc.

First, let’s autowire the WebApplicationContext in our unit test class:

private WebApplicationContext webApplicationContext;

Now, let’s write a method to test the multipart POST request defined above:

public void whenFileUploaded_thenVerifyStatus() 
  throws Exception {
    MockMultipartFile file 
      = new MockMultipartFile(
        "Hello, World!".getBytes()

    MockMvc mockMvc 
      = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

Here, we’re defining a hello.txt file using MockMultipartFile constructor, then we’re building the mockMvc object using the webApplicationContext object defined earlier.

We’ll use the MockMvc#perform method to call the REST Endpoint and pass it the file object. Finally, we’ll check the status code 200 to verify our test case.

4. Conclusion

In this article, we’ve seen how to test a Spring Multipart POST Request using MockMvc with the help of an example.

As always the project is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.