1

I am trying to write Junit tests for a Controller class which contains the following method.

 @RequestMapping(value = "/mappingUrl", method = RequestMethod.POST)
public String uploadFileMethod(HttpServletResponse httpResponse, HttpServletRequest httpRequest, ModelMap model) throws Exception {

  try {
    MultipartFile multipartFile = ((MultipartHttpServletRequest) httpRequest).getFile("fileName");
   }
  catch(Exception e){}
}

In the test class I have the following method

 @Test
public void testUploadFileMethod() throws Exception {
mockMVC.perform(post("/mappingUrl")).andExpect(status().isOk());
}

I am getting the the below exception when the test is executed:

java.lang.ClassCastException: org.springframework.mock.web.MockHttpServletRequest cannot be cast to org.springframework.web.multipart.MultipartHttpServletRequest

Is there a way I can test the method without changing the existing code? The class is used through out the application and I am afraid I might break something else.

I went through questions that were similar and the following are the ones that came close:

Mockito ClassCastException - A mock cannot be cast

pass remoteUser value in HttpServletRequest to mockmvc perform test

wardaddy
  • 383
  • 1
  • 4
  • 16
  • See https://stackoverflow.com/questions/21800726/using-spring-mvc-test-to-unit-test-multipart-post-request – M. Deinum Jul 25 '18 at 05:25
  • Depending on the Spring Version use `multipart` (for Spring 5) else use `fileUpload` as a factory method. – M. Deinum Jul 25 '18 at 05:29

1 Answers1

0

Just try

MockMultipartFile myFile = new MockMultipartFile("data", "myFile.txt", "text/plain", "myFileContent".getBytes());
mockMVC.perform(MockMvcRequestBuilders.multipart("/mappingUrl")
                    .file(myFile)).andExpect(status().isOk());

as explained here

Halko Karr-Sajtarevic
  • 2,248
  • 1
  • 16
  • 14
  • It says `The method multipart(String) is undefined for the type MockMvcRequestBuilders` – wardaddy Jul 24 '18 at 14:00
  • 1
    Ah got it..sorry I skipped the first line of the linked answer. **Since MockMvcRequestBuilders#fileUpload is deprecated**. I am acutally using an older version of java and `mockMVC.perform(MockMvcRequestBuilders.fileUpload("/mappingUrl") .file(myFile)).andExpect(status().isOk());` worked for me. – wardaddy Jul 25 '18 at 05:37