如何使用 MockHttpServletRequest 对文件上传进行单元测试?
我有一个 Spring (3.0) 控制器,其方法将 HttpServletRequest 作为参数之一,因为它正在处理(多个)文件上传。
@RequestMapping(value = "/classified/{idClassified}/dealer/{idPerson}/upload",
method = RequestMethod.POST)
@ResponseBody
public final String uploadClassifiedPicture(
@PathVariable int idClassified,
@PathVariable int idPerson,
@RequestParam String token,
HttpServletRequest request);
如何进行单元测试?我知道我可以创建一个 MockHttpServletRequest
,但我不知道如何将一个或多个文件传递给它。
MockHttpServletRequest request = new MockHttpServletRequest("POST",
"/classified/38001/dealer/54/upload?token=dfak241adf");
I've a Spring (3.0) Controller with a method which has HttpServletRequest
as one of the parameters, since it's handling (multiple) file uploads.
@RequestMapping(value = "/classified/{idClassified}/dealer/{idPerson}/upload",
method = RequestMethod.POST)
@ResponseBody
public final String uploadClassifiedPicture(
@PathVariable int idClassified,
@PathVariable int idPerson,
@RequestParam String token,
HttpServletRequest request);
How to Unit Test it? I know I can create a MockHttpServletRequest
, but I don't know how to pass one or more files to it.
MockHttpServletRequest request = new MockHttpServletRequest("POST",
"/classified/38001/dealer/54/upload?token=dfak241adf");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议稍微更改方法签名,以使上传的文件成为普通参数(类型为
MultipartFile
(不是CommonsMultipartFile
)):那么你可以使用
MockMultipartFile
在您的测试中:如果您不想更改方法签名,那么您可以使用
MockMultipartHttpServletRequest
反而。它有一个方法
addFile(MultipartFile 文件)
。当然,所需参数可以是MockMultipartFile
。I recommend to change the method signature a bit, to make the uploaded file a normal parameter (of type
MultipartFile
(notCommonsMultipartFile
)):Then you can use a
MockMultipartFile
in your test:If you do not want to change the method signature, then you can use
MockMultipartHttpServletRequest
instead.It has a method
addFile(MultipartFile file)
. And of course the required parameter can be aMockMultipartFile
.您还可以使用 MockMvc 对象以及 MockMvcRequestBuilders 向控制器发送测试文件上传请求:
You can also use the MockMvc object as well as MockMvcRequestBuilders to send a test file upload request to your controller: