当前位置: 首页 > 知识库问答 >
问题:

无法用Spring Boot Test测试MockMultipartFile-找不到序列化程序

淳于亦
2023-03-14

我试图模拟将图像上传到控制器endpoint,该endpoint期望DTO包含一个MultipartFile输入和几个纯文本字段。但我似乎不能模拟一个要发送的多部分文件:

下面是我的测试:

 @Test
  public void saveAnEntryWhenPOSTNewUserWithAPicture() throws Exception {
    MockMultipartFile multiPFImage = new MockMultipartFile("contactImgUpload", "abcpic.png",
            "text/plain", "Generate bytes to simulate a picture".getBytes());
    mockMvc.perform(MockMvcRequestBuilders.fileUpload("/newContact")
            .file(multiPFImage)
            .contentType(MediaType.MULTIPART_FORM_DATA)
            .param("userId", "12345")
            .param("name", "Picture Uploader User"))
            .andExpect(status().isOk())
            .andExpect(content().string(containsString("Picture Uploader User")))
            .andExpect(content().string(containsString("Replace with image title")));
  }
@PostMapping(path = "/newContact")
  public @ResponseBody ContactDTO createNewContact(@ModelAttribute ContactDTO newContact) {

   //converts newContact to DAO and persists to DB

   return newContact
}
public class ContactDTO implements Serializable {

  private BigInteger userId;
  private BigInteger contactId; //automatically generated on persistence
  private String name;
  private MultipartFile contactImgUpload;
}

共有1个答案

蒲坚
2023-03-14

您可以使用以下内容:

@Autowired
private ObjectMapper mapper;

@Before
public void before() {
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
 类似资料: