Cannot Test MockMultipartFile with Spring Boot Test - No serializer found
我正在尝试模拟将图像上传到控制器端点,该控制器期望DTO包含MultipartFile输入以及几个纯文本字段。但我似乎无法模拟要发送的MultipartFile:
这是我的考试:
1 2 3 4 5 6 7 8 9 10 11 12 13 | @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"))); } |
我们正在测试的控制器方法:
1 2 3 4 5 6 7 | @PostMapping(path ="/newContact") public @ResponseBody ContactDTO createNewContact(@ModelAttribute ContactDTO newContact) { //converts newContact to DAO and persists to DB return newContact } |
要转换的DTO:
1 2 3 4 5 6 7 | public class ContactDTO implements Serializable { private BigInteger userId; private BigInteger contactId; //automatically generated on persistence private String name; private MultipartFile contactImgUpload; } |
运行测试时,它失败,并且我收到以下消息:
.w.s.m.s.DefaultHandlerExceptionResolver : Failed to write HTTP
message:
org.springframework.http.converter.HttpMessageNotWritableException:
Could not write JSON: No serializer found for class
java.io.ByteArrayInputStream and no properties discovered to create
BeanSerializer (to avoid exception, disable
SerializationFeature.FAIL_ON_EMPTY_BEANS); nested exception is
com.fasterxml.jackson.databind.JsonMappingException: No serializer
found for class java.io.ByteArrayInputStream and no properties
discovered to create BeanSerializer (to avoid exception, disable
SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain:
app.models.dto.ContactDTO["contactImgUpload"]->org.springframework.mock.web.MockMultipartFile["inputStream"])
我已经看到过这个问题的其他几个实例,但是大多数都没有答案,或者答案不尽相同。关于如何测试需要绑定到DTO的MockMultipartFile的任何想法?
您可以使用此:
1 2 3 4 5 6 7 | @Autowired private ObjectMapper mapper; @Before public void before() { mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); } |