HttpServletRequest 到 MultipartHttpServletRequest:Junit 中的 ClassCastException

HttpServletRequest to MultipartHttpServletRequest: ClassCastException in Junit

我正在尝试为包含以下方法的控制器 class 编写 Junit 测试。

 @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){}
}

在测试中class我有以下方法

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

执行测试时出现以下异常:

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

有没有一种方法可以在不更改现有代码的情况下测试该方法? class 在整个应用程序中使用,恐怕我可能会破坏其他东西。

我回答了一些类似的问题,以下是比较接近的问题:

将HttpServletRequest中的remoteUser值传递给mockmvc进行测试

试试

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

如解释的那样here