Search code examples
javarestjunitmultipart

How to test REST API with MultiPart parameter using junit?


I need some help over testing POST REST function,

I got this REST function header:

@RequestMapping(value = "/import", method = RequestMethod.POST)
    public @ResponseBody
    HistoricalDataImportResponse importHistoricalDataFile(String fileFormat, @RequestParam("file") MultipartFile stream)  {

And I tried test it using JUnit with this test:

@Test
public void testHistoricalDataImport() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    FileItem fileItem = new DiskFileItem(null, null, false, null, 0, null);
    MultipartFile eventRequest = new CommonsMultipartFile(null);
    String body = mapper.writeValueAsString(eventRequest);

    //when
    MvcResult result = this.mockMvc.perform(post("/historicaldata/import").contentType(MediaType.MULTIPART_FORM_DATA).content(body))
            .andExpect(status().isOk())
            .andReturn();
}

The fileItem is null while running the test, how do I need to pass some file to my REST function ?


Solution

  • The final test as follows:

     @Test
        public void testHistoricalDataImport() throws Exception {
            MockMultipartFile firstFile = new MockMultipartFile("file", "filename.csv", "text/plain", "some CSV data".getBytes());
            MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.fileUpload("/historicaldata/import")
                    .file(firstFile);
    
            MvcResult result = mockMvc.perform(requestBuilder)
                    .andExpect(status().isOk())
                    .andReturn();
        }