spring-boot - MockMvc 不再使用 Spring Boot 2.2.0.RELEASE 处理 UTF-8 字符

标签 spring-boot spring-mvc jackson spring-test

在我升级到新发布的2.2.0.RELEASE之后我的一些测试失败的 Spring Boot 版本。看来 MediaType.APPLICATION_JSON_UTF8已被弃用,不再作为默认内容类型从未明确指定内容类型的 Controller 方法返回。

测试代码如

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."}]

我怎样才能得到content在 UTF-8 编码中?

最佳答案

是的。这是 2.2.0 spring-boot 的问题。他们为默认字符集编码设置了弃用。
.getContentAsString(StandardCharsets.UTF_8) - 很好,但在任何响应中,默认情况下都会填充 ISO 8859-1。

在我的项目中,我更新了当前创建的转换器:

@Configuration
public class SpringConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.stream()
            .filter(converter -> converter instanceof MappingJackson2HttpMessageConverter)
            .findFirst()
            .ifPresent(converter -> ((MappingJackson2HttpMessageConverter) converter).setDefaultCharset(UTF_8));
    }
...

关于spring-boot - MockMvc 不再使用 Spring Boot 2.2.0.RELEASE 处理 UTF-8 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58525387/

相关文章:

java - org.hibernate.LazyInitializationException : failed to lazily initialize a collection of role while using Javers

spring-mvc - 从应用服务层报告错误

java - Hibernate 不会在内连接中返回正确的对象

java - 如果枚举映射键为 null 或未知,则忽略 JSON 反序列化

java - Jackson 将子 JSON 反序列化为父属性

spring-security - Spring Boot - Redis 持久化 token

java - 测试Web层时模拟 Controller 类的方法

Spring HATEOAS RepresentationModelAssembler toCollectionModel()

spring - nginx反向代理+Spring ResourceSupport产生错误的URL路径前缀

java - Jackson 解析中对象值为 null