6

I've created a controller that would consume a 'multipart/form-data'

@PostMapping(value="/sample")
public void sample(
    @ModelAttribute("request") SampleRequest request){
    // codes
}

SampleRequest object

@NotNull
private MultipartFile file;

@Pattern(regexp = "^[0-9A-Za-z]*")
private String fileName;

private String other;

And now, I will try to test it using Mock MVC but I don't know how to pass 'multipart/form-data' as content. I saw a lot of sample using JSON but not with multipart/form-data

mockMvc.perform(post(path)
        .servletPath(path)
        .headers(headers)
        .contentType(MediaType.MULTIPART_FORM_DATA)
        .content(request)) // -> How to put the multipart/form-data here
        .andDo(print())
        .andReturn();

Is there a way I can complete my request with multipart/form_data? Ideally it needs to be in the body of MockHttpServletRequest

MockHttpServletRequest:
  HTTP Method = POST
  Request URI = --path
  Parameters = {}
  Headers = --headers
  Body = null
jawsh
  • 163
  • 2
  • 11
  • This might help you: https://stackoverflow.com/questions/21800726/using-spring-mvc-test-to-unit-test-multipart-post-request – Jj Tuibeo Apr 17 '20 at 09:48

1 Answers1

10

I've managed to do it that way:

      Resource fileResource = new ClassPathResource("YOUR FILE NAME");
    
      assertNotNull(fileResource);

      MockMultipartFile firstFile = new MockMultipartFile( 
            "file",fileResource.getFilename(),
             MediaType.MULTIPART_FORM_DATA_VALUE,
             fileResource.getInputStream());  
    
     assertNotNull(firstFile);
    
     MockMvc mockMvc = MockMvcBuilders.
             webAppContextSetup(webApplicationContext).build();

     MvcResult andReturn = mockMvc.perform(MockMvcRequestBuilders
           .multipart(**YOUR URL**)
           .file(firstFile)
           .headers(**YOUR HEADERS**))
            .andDo(print())
            .andExpect(status().isOk())
            .andReturn();

I've seen this example here:

https://www.baeldung.com/spring-multipart-post-request-test

Vitor Muniz
  • 146
  • 2
  • 7