gpt4 book ai didi

java - 无法使用 Spring Boot 测试测试 MockMultipartFile - 找不到序列化器

转载 作者:行者123 更新时间:2023-11-30 02:21:32 28 4
gpt4 key购买 nike

我正在尝试模拟将图像上传到 Controller 端点,该端点需要包含 MultipartFile 输入以及多个纯文本字段的 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")));
}

我们正在测试的 Controller 方法:

@PostMapping(path = "/newContact")
public @ResponseBody ContactDTO createNewContact(@ModelAttribute ContactDTO newContact) {

//converts newContact to DAO and persists to DB

return newContact
}

用于转换的DTO:

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"])

我见过这个问题的其他几个实例,但大多数都没有答案,或者并不完全相同。关于如何测试需要绑定(bind)到 DTO 的 MockMultipartFile 有什么想法吗?

最佳答案

你可以使用这个:

@Autowired
private ObjectMapper mapper;

@Before
public void before() {
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}

关于java - 无法使用 Spring Boot 测试测试 MockMultipartFile - 找不到序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46692859/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com