Reputation: 43
When i'm testing just trivial POST-requests, i can get MvcResult and get something from it:
MvcResult result = mockMvc.perform(post("/api/register")
.contentType(MEDIA_TYPE_JSON_UTF8)
.content(new Gson().toJson(request)))
.andExpect(status().isCreated())
.andReturn();
Long tempId = Long.valueOf(JsonPath.read(result.getResponse().getContentAsString(), "$.id").toString());
But when i'm using MultipartFile, i can only use MockMvcRequestBuilders and only check expectations.
MockMultipartFile filePart = new MockMultipartFile(
"file",
"file.jpg",
"image/jpeg", file);
mockMvc.perform(MockMvcRequestBuilders.multipart("/api/loadfile")
.file(filePart)
.param("json", json))
.andExpect(status().isOk());
How can i get MvcResult with multipart POST after request?
Upvotes: 1
Views: 547
Reputation: 12021
You can call .andReturn();
right after .andExpect()
like you did it in the trivial POST example.
Calling mockMvc.perform()
returns a ResultActions
object independent of any HTTP method or request.
The following example works with Spring Boot 2.3.0:
byte[] file = new byte[10];
MockMultipartFile filePart = new MockMultipartFile(
"file", "file.jpg", "image/jpeg", file);
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.multipart("/api/loadfile")
.file(filePart)
.param("json", "json"))
.andExpect(status().isOk())
.andReturn();
Upvotes: 2