Andremoniy Andremoniy - 17 days ago 5
Java Question

How to PUT multipart/form-data using Spring MockMvc?

I have controller's method with

PUT
method, which receives multipart/form-data:

@RequestMapping(value = "/putIn", method = RequestMethod.PUT)
public Foo updateFoo(HttpServletRequest request,
@RequestBody Foo foo,
@RequestParam("foo_icon") MultipartFile file) {
...
}


and I want to test it using
MockMvc
. Unfortunately
MockMvcRequestBuilders.fileUpload
creates essentially instance of
MockMultipartHttpServletRequestBuilder
which has
POST
method:

super(HttpMethod.POST, urlTemplate, urlVariables)


EDIT:
Surely I can I can not create my own implementation of
MockHttpServletRequestBuilder
, say

public MockPutMultipartHttpServletRequestBuilder(String urlTemplate, Object... urlVariables) {
super(HttpMethod.PUT, urlTemplate, urlVariables);
super.contentType(MediaType.MULTIPART_FORM_DATA);
}


because
MockHttpServletRequestBuilder
has package-local constructor.

But I'm wondering is any more convenient Is any way to do this, may be I missed some existent class or method for doing it?

Answer

This is unfortunately currently not supported in Spring MVC Test, and I don't see a work-around other than creating your own custom MockPutMultipartHttpServletRequestBuilder and copying-n-pasting code from the standard implementation.

For what it's worth, Spring MVC also does not support PUT requests for file uploads by default either. The Multipart resolvers are hard coded to accept only POST requests for file uploads -- both for Apache Commons and the standard Servlet API support.

If you would like Spring to support PUT requests in addition, feel free to open a ticket in Spring's JIRA issue tracker.

Comments