gpt4 book ai didi

java - HttpServletRequest 到 MultipartHttpServletRequest : ClassCastException in Junit

转载 作者:太空宇宙 更新时间:2023-11-04 10:17:37 25 4
gpt4 key购买 nike

我正在尝试为包含以下方法的 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

最佳答案

尝试一下

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

如所解释的here

关于java - HttpServletRequest 到 MultipartHttpServletRequest : ClassCastException in Junit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51499904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com