【问题标题】:HttpServletRequest to MultipartHttpServletRequest: ClassCastException in Junit [duplicate]HttpServletRequest 到 MultipartHttpServletRequest:Junit 中的 ClassCastException [重复]
【发布时间】:2019-01-01 03:38:38
【问题描述】:

我正在尝试为包含以下方法的 Controller 类编写 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){}
}

在测试类中我有以下方法

 @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

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

我遇到了类似的问题,以下是接近的问题:

Mockito ClassCastException - A mock cannot be cast

pass remoteUser value in HttpServletRequest to mockmvc perform test

【问题讨论】:

标签: java spring junit mockito classcastexception


【解决方案1】:

试试吧

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

如解释here

【讨论】:

  • 上面写着The method multipart(String) is undefined for the type MockMvcRequestBuilders
  • 啊,明白了..对不起,我跳过了链接答案的第一行。 由于 MockMvcRequestBuilders#fileUpload 已弃用。我正在使用旧版本的 java 和 mockMVC.perform(MockMvcRequestBuilders.fileUpload("/mappingUrl") .file(myFile)).andExpect(status().isOk()); 为我工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-15
  • 1970-01-01
  • 2012-01-14
  • 2016-04-01
  • 1970-01-01
  • 2016-07-21
相关资源
最近更新 更多