为了账号安全,请及时绑定邮箱和手机立即绑定

HttpServletRequest 到 MultipartHttpServletRequest:

HttpServletRequest 到 MultipartHttpServletRequest:

手掌心 2021-06-08 13:27:48
我正在尝试为包含以下方法的 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){}}在测试类中,我有以下方法 @Testpublic 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有没有一种方法可以在不更改现有代码的情况下测试该方法?该类在整个应用程序中使用,我担心我可能会破坏其他东西。
查看完整描述

1 回答

?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

你试一试


MockMultipartFile myFile = new MockMultipartFile("data", "myFile.txt", "text/plain", "myFileContent".getBytes());

mockMVC.perform(MockMvcRequestBuilders.multipart("/mappingUrl")

                    .file(myFile)).andExpect(status().isOk());

正如这里所解释的


查看完整回答
反对 回复 2021-06-10
  • 1 回答
  • 0 关注
  • 564 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信