我正在嘗試為包含以下方法的 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());}執(zhí)行測試時出現(xiàn)以下異常:java.lang.ClassCastException: org.springframework.mock.web.MockHttpServletRequest cannot be cast to org.springframework.web.multipart.MultipartHttpServletRequest有沒有一種方法可以在不更改現(xiàn)有代碼的情況下測試該方法?該類在整個應(yīng)用程序中使用,我擔(dān)心我可能會破壞其他東西。
1 回答

拉風(fēng)的咖菲貓
TA貢獻(xiàn)1995條經(jīng)驗 獲得超2個贊
你試一試
MockMultipartFile myFile = new MockMultipartFile("data", "myFile.txt", "text/plain", "myFileContent".getBytes());
mockMVC.perform(MockMvcRequestBuilders.multipart("/mappingUrl")
.file(myFile)).andExpect(status().isOk());
正如這里所解釋的
添加回答
舉報
0/150
提交
取消