【发布时间】:2020-02-19 20:24:42
【问题描述】:
在我升级到新发布的2.2.0.RELEASE 版本的 Spring Boot 后,我的一些测试失败了。 MediaType.APPLICATION_JSON_UTF8 似乎已被弃用,并且不再作为默认内容类型从未明确指定内容类型的控制器方法返回。
类似的测试代码
String content = mockMvc.perform(get("/some-api")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andReturn()
.getResponse()
.getContentAsString();
由于内容类型不匹配,突然不再起作用,如下所示
java.lang.AssertionError: Content type
Expected :application/json;charset=UTF-8
Actual :application/json
将代码更改为.andExpect(content().contentType(MediaType.APPLICATION_JSON)) 暂时解决了该问题。
但是现在当比较content 和预期的序列化对象时,如果对象中有任何特殊字符,仍然会出现不匹配。 .getContentAsString() 方法似乎默认(不再)使用 UTF-8 字符编码。
java.lang.AssertionError: Response content expected:<[{"description":"Er hörte leise Schritte hinter sich."}]> but was:<[{"description":"Er hörte leise Schritte hinter sich."}]>
Expected :[{"description":"Er hörte leise Schritte hinter sich."}]
Actual :[{"description":"Er hörte leise Schritte hinter sich."}]
如何以 UTF-8 编码获得content?
【问题讨论】:
标签: spring-boot spring-mvc jackson spring-test