Spring 中的集成测试期间的 MultipartFile#getContentType returns null

MultipartFile#getContentType returns null during integration tests in Spring

我有以下文件:

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));
    }
}
  1. 测试中GallerControllerIT#createImage_POSTHttpMethod_ImageIsCreated 我设置了一个文件。
  2. 测试发送文件到GalleryController#createImage并映射 到 ImageForm#file 属性。
  3. ImageForm#file 的类型 MultipartFile 具有方法 getContentType
  4. 方法MultipartFile#getContentTypereturnsnull.

问题是,为什么 MultipartFile#getContentType return 为空?它在测试之外正常工作。

要获得完整数据,您应该致电

.file(new MockMultipartFile("image", "some_name", MediaType.MULTIPART_FORM_DATA_VALUE, image))

因为在你的情况下,如果你调用 .file("file", image) 他们调用构造函数的短版本 MockMultipartFile 没有内容类型

MockMvc 尝试不创建或声明一些额外的值或参数,如果你没有声明它们的话。