У меня есть следующие файлы:
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 возвращает ноль? Он работает правильно, когда вне теста.




Для получения полных данных звоните
.file(new MockMultipartFile("image", "some_name", MediaType.MULTIPART_FORM_DATA_VALUE, image))
Потому что под капотом в вашем случае, если вы вызываете .file("file", image), они вызывают короткую версию конструктора MockMultipartFile без типа контента
MockMvc стараться не создавать и не объявлять какие-то дополнительные значения или параметры, если вы их не объявляете.
Спасибо, это была проблема.