java 如何使用 MockHttpServletRequest 对文件上传进行单元测试?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7879620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to unit test file uploads with MockHttpServletRequest?
提问by stivlo
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.
我有一个 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);
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
,但我不知道如何将一个或多个文件传递给它。
MockHttpServletRequest request = new MockHttpServletRequest("POST",
"/classified/38001/dealer/54/upload?token=dfak241adf");
回答by Ralph
I recommend to change the method signature a bit, to make the uploaded file a normal parameter (of type MultipartFile
(not CommonsMultipartFile
)):
我建议稍微更改方法签名,以使上传的文件成为普通参数(类型(not )):MultipartFile
CommonsMultipartFile
@RequestMapping(value = "/classified/{idClassified}/dealer/{idPerson}/upload",
method = RequestMethod.POST)
@ResponseBody
public final String uploadClassifiedPicture(
@PathVariable int idClassified,
@PathVariable int idPerson,
@RequestParam String token,
@RequestParam MultipartFile content);
Then you can use a MockMultipartFile
in your test:
然后你可以MockMultipartFile
在你的测试中使用 a :
final String fileName = "test.txt";
final byte[] content = "Hallo Word".getBytes();
MockMultipartFile mockMultipartFile =
new MockMultipartFile("content", fileName, "text/plain", content);
uploadClassifiedPicture(1, 1, "token", mockMultipartFile);
If you do not want to change the method signature, then you can use MockMultipartHttpServletRequest
instead.
如果不想更改方法签名,则可以MockMultipartHttpServletRequest
改用。
It has a method addFile(MultipartFile file)
. And of course the required parameter can be a MockMultipartFile
.
它有一个方法addFile(MultipartFile file)
。当然,所需的参数可以是MockMultipartFile
.
回答by jfcorugedo
You can also use the MockMvc object as well as MockMvcRequestBuilders to send a test file upload request to your controller:
您还可以使用 MockMvc 对象以及 MockMvcRequestBuilders 向您的控制器发送测试文件上传请求:
@Test
public void testSendNotEmptyFile() throws Exception {
mvc.perform(MockMvcRequestBuilders.fileUpload("Your controller URL")
.file("file", "Test Content".getBytes())
.contentType(MediaType.MULTIPART_FORM_DATA)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}