【问题标题】:MultipartFile#getContentType returns null during integration tests in SpringMultipartFile#getContentType 在 Spring 的集成测试期间返回 null
【发布时间】: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));
    }
}
  1. 测试中GallerControllerIT#createImage_POSTHttpMethod_ImageIsCreated 我设置了一个文件。
  2. 测试将文件发送到GalleryController#createImage并映射它 到ImageForm#file 属性。
  3. ImageForm#fileMultipartFile 类型,它有方法 getContentType
  4. 方法MultipartFile#getContentType返回null

问题是,为什么MultipartFile#getContentType 返回null?在测试之外它可以正常工作。

【问题讨论】:

    标签: java spring integration-testing spring-test


    【解决方案1】:

    对于完整的数据,你应该调用

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

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

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

    【讨论】:

    • 谢谢,这就是问题所在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多