Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

Generic Top

Get started with Spring 5 and Spring Boot 2, 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.

Generic bottom

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

Generic footer banner
Comments are closed on this article!