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");
I recommend to change the method signature a bit, to make the uploaded file a normal parameter (of type MultipartFile
(not 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:
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.
It has a method addFile(MultipartFile file)
. And of course the required parameter can be a MockMultipartFile
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With