Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test file uploads with MockHttpServletRequest?

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");
like image 718
stivlo Avatar asked Oct 24 '11 17:10

stivlo


1 Answers

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.

like image 130
Ralph Avatar answered Nov 05 '22 12:11

Ralph