Issue
I'm trying to test (through Spring test (mvc)) a controller that uses servletRequest.getParts()
All I've read so far is that MockMvcRequestBuilders.fileUpload().file()
is the solution. However I cannot make it work. I wrote the following test which fails
MockMultipartHttpServletRequestBuilder builder = MockMvcRequestBuilders.fileUpload("/foo")
.file(new MockMultipartFile("file", new byte[] { 1, 2, 3, 4 }));
MockHttpServletRequest rq = builder.buildRequest(null);
Assert.assertEquals(1, rq.getParts().size()); // result 0
I went through spring code, and the call to file(...)
adds an element in List<MockMultipartFile>
when getParts()
gets its elements from another list (Map<String, Part> parts)
There must be another way to do it...
Edit 1
The code I'm using to test the controller is :
ResultActions result = mockMvc.perform(
MockMvcRequestBuilders.fileUpload(new URI("/url")).file("param", "expected".getBytes()))
Solution
There is currently no support for testing with javax.servlet.http.Part
in the Spring MVC Test Framework.
Consequently, I have introduced two tickets to address this shortcoming in Spring Framework 5.0:
In the interim, you should be able to mock Part
yourself and register it in the prepared MockHttpServletRequest
via a custom RequestPostProcessor
.
Regards,
Sam (author of the Spring TestContext Framework)
Answered By - Sam Brannen
Answer Checked By - Robin (JavaFixing Admin)