【发布时间】:2019-05-13 17:34:36
【问题描述】:
我有以下文件:
ImageForm.java:
public class ImageForm {
@FileNotEmpty
private MultipartFile file;
// other code ...
}
GalleryController.java:
@Controller
@RequestMapping("/admin/galleries")
public class GalleryController {
@PostMapping("/{id}/image/create")
public ModelAndView createImage(@PathVariable("id") long galleryId, @Valid ImageForm imageForm, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
// other code ...
System.out.println(imageForm.getFile().getContentType()); // Prints: null
// other code ...
}
}
GalleryControllerIT.java:
@SqlGroup({
@Sql("classpath:test-schema.sql"),
@Sql("classpath:test-gallery-data.sql"),
@Sql("classpath:test-image-data.sql")
})
public class GalleryControllerIT extends SetupControllerIT {
@Test
public void createImage_POSTHttpMethod_ImageIsCreated() throws Exception {
Path path = Paths.get(getClass().getClassLoader().getResource("test-image.png").toURI());
byte[] image = Files.readAllBytes(path);
mvc.perform(
multipart("/admin/galleries/1/image/create")
.file("file", image) // TODO: ImageForm.file.contentType is null.
.with(csrf())
).andExpect(status().isFound());
assertThat(imageRepository.count(), is(5L));
}
}
- 测试中
GallerControllerIT#createImage_POSTHttpMethod_ImageIsCreated我设置了一个文件。 - 测试将文件发送到
GalleryController#createImage并映射它 到ImageForm#file属性。 -
ImageForm#file是MultipartFile类型,它有方法getContentType。 - 方法
MultipartFile#getContentType返回null。
问题是,为什么MultipartFile#getContentType 返回null?在测试之外它可以正常工作。
【问题讨论】:
标签: java spring integration-testing spring-test