I'm trying to unit test a controller which takes an request object of type ArticleForm
and it contains a list of MultipartFile
.
Here is the controller method that I'm trying to test.
@RequestMapping(value = "/admin/save", method = RequestMethod.POST)
public String save(@ModelAttribute @Valid ArticleForm articleForm,
BindingResult result, RedirectAttributes redirectAttributes) {
....
}
Below is the Model attribute object ArticleForm
public class ArticleForm {
private String id;
@NotEmpty
private String title;
@NotEmpty
private String description;
private List<MultipartFile> images = Collections.emptyList();
}
In my unit test, I want to submit 3 MockMulitpartFile
objects as well as title
and description
Here is what I have tried. The title
and description
gets populated but the images
list is empty
@Test
public void adminController_saveArticleWithTitleAndDescription() throws Exception {
final MockMultipartFile multipartFile1 = new MockMultipartFile("image1", "image1", "image/png", getResourceAsStream("/images/image1.png"));
final MockMultipartFile multipartFile2 = new MockMultipartFile("image2", "image2", "image/png", getResourceAsStream("/images/image2.png"));
final MockMultipartFile multipartFile3 = new MockMultipartFile("image3", "image3", "image/jpeg", getResourceAsStream("/images/image2.png"));
mockMvc.perform(fileUpload("/admin/save")
.file(multipartFile1)
.file(multipartFile2)
.file(multipartFile3)
.contentType(MediaType.MULTIPART_FORM_DATA)
.param("title", "Integration Testing")
.param("description", "This is an integration test"))
.andExpect(flash().attribute(FLASH_TYPE, is(FLASH_TYPE_SUCCESS)))
.andExpect(flash().attribute(FLASH_MESSAGE, is(msgs.getMessage("controller.admin.save.success"))))
.andExpect(status().isFound())
.andExpect(view().name("redirect:/admin/add"));
}
How can I submit those 3 MockMultipartFile
objects to the images
list in the ArticleForm
model attribute ?
Appreciate any help to resolve this issue.
Your test is correct. Use "images" for the file name like below.
final MockMultipartFile multipartFile1 = new MockMultipartFile("images", "image1", "image/png", getResourceAsStream("/images/image1.png"));
final MockMultipartFile multipartFile2 = new MockMultipartFile("images", "image2", "image/png", getResourceAsStream("/images/image2.png"));
final MockMultipartFile multipartFile3 = new MockMultipartFile("images", "image3", "image/jpeg", getResourceAsStream("/images/image2.png"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.