Tested with spring boot 2.3.4.
Example project
We have controller that receives some arguments that are parts of multipart request.
@RestController
class HelloWorldController {
@RequestMapping(path = "helloworld", method = RequestMethod.POST)
@ResponseStatus(code = HttpStatus.OK)
public String helloWorld(@RequestPart(name = "part0") String str0,
@RequestPart(name = "part1") String str1) {
return str0+str1;
}
}
For running application request works as intended:
POST http://localhost:8080/helloworld
Content-Type: multipart/form-data; boundary=6512c604-1edc-4c15-8916-dc2e91413c82
--6512c604-1edc-4c15-8916-dc2e91413c82
Content-Disposition: form-data;name="part0"
Content-Type: text/plain
Hello
--6512c604-1edc-4c15-8916-dc2e91413c82
Content-Disposition: form-data;name="part1"
Content-Type: text/plain
World
--6512c604-1edc-4c15-8916-dc2e91413c82--
## response HelloWorld
Now we want to test it:
@Test
void helloWorldTest() throws Exception {
MockPart part0 = new MockPart("part0", "Hello".getBytes());
part0.getHeaders().setContentType(MediaType.TEXT_PLAIN);
MockPart part1 = new MockPart("part1", "World".getBytes());
part1.getHeaders().setContentType(MediaType.TEXT_PLAIN);
web.perform(multipart("/helloworld")
.part(part0, part1))
.andExpect(status().isOk())
.andExpect(content().string("HelloWorld"));
}
But test is failing with NPE exception:
Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
Caused by: java.lang.NullPointerException
at org.springframework.web.multipart.support.RequestPartServletServerHttpRequest.getBody(RequestPartServletServerHttpRequest.java:99)
The reason behind that is org.springframework.web.multipart.support.RequestPartServletServerHttpRequest:84; it's expecting StandardMultipartHttpServletRequest in multipartRequest field but got MockMultipartHttpServletRequest:
public InputStream getBody() throws IOException {
if (this.multipartRequest instanceof StandardMultipartHttpServletRequest) {
try {
return this.multipartRequest.getPart(this.partName).getInputStream();
}
catch (Exception ex) {
throw new MultipartException("Could not parse multipart servlet request", ex);
}
}
<...>
}
Tested with spring boot 2.3.4.
Example project
We have controller that receives some arguments that are parts of multipart request.
For running application request works as intended:
Now we want to test it:
But test is failing with NPE exception:
The reason behind that is
org.springframework.web.multipart.support.RequestPartServletServerHttpRequest:84; it's expectingStandardMultipartHttpServletRequestinmultipartRequestfield but gotMockMultipartHttpServletRequest: