How to add file to MockMvc [duplicate]

Solution 1:

public void testAddContacts() throws Exception{
            File f = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg");
            System.out.println(f.isFile()+"  "+f.getName()+f.exists());
            FileInputStream fi1 = new FileInputStream(f);
            FileInputStream fi2 = new FileInputStream(new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Tulips.jpg"));
            MockMultipartFile fstmp = new MockMultipartFile("upload", f.getName(), "multipart/form-data",fi1);
            MockMultipartFile secmp = new MockMultipartFile("upload", "Tulips.jpg","multipart/form-data",fi2); 
            MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
            mockMvc.perform(MockMvcRequestBuilders.fileUpload("/AddContacts")                
                    .file(fstmp)
                    .file(secmp)
                    .param("name","abc").param("email","[email protected]").param("phone", "1234567890"))               
                    .andExpect(status().isOk());
    }

Solution 2:

The method MockMvcRequestBuilders.fileUpload is deprecated

fileUpload @Deprecated public static
MockMultipartHttpServletRequestBuilder fileUpload(java.net.URI uri)
Deprecated. in favor of multipart(URI) Create a
MockMultipartHttpServletRequestBuilder for a multipart request.
Parameters: uri - the URL Since:
4.0.3

To instead of fileUpload(), use this way.

  MockMultipartFile mockMultipartFile = new MockMultipartFile("user-file",fileName,
          "text/plain", "test data".getBytes());

  MockHttpServletRequestBuilder builder =
          MockMvcRequestBuilders.multipart("/upload")
                                .file(mockMultipartFile);

Or

MockMultipartFile jsonFile = new MockMultipartFile("test.json", "", "application/json", "{\"key1\": \"value1\"}".getBytes());

mockMvc.perform(MockMvcRequestBuilders.multipart("/fileUpload")
                .file("file", jsonFile.getBytes())
                .characterEncoding("UTF-8"))