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:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.1.16.RELEASE</version>
    <scope>test</scope>
</dependency>

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:

@Autowired
private WebApplicationContext webApplicationContext;

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

@Test
public void whenFileUploaded_thenVerifyStatus() 
  throws Exception {
    MockMultipartFile file 
      = new MockMultipartFile(
        "file", 
        "hello.txt", 
        MediaType.TEXT_PLAIN_VALUE, 
        "Hello, World!".getBytes()
      );

    MockMvc mockMvc 
      = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    mockMvc.perform(multipart("/upload").file(file))
      .andExpect(status().isOk());
}

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.