You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级spring-test 5.3.12后MockMVC返回ContentType异常导致测试失败如何解决

解决方案
  • 方案1:修改测试断言为兼容匹配(改法最小,优先推荐)
    把原有断言里的content().contentType(MediaType.APPLICATION_JSON)替换为content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)即可。
    这个方法会自动忽略ContentType的额外参数(比如charset),仅匹配主类型application和子类型json,完全符合你的验证场景,不需要修改任何框架配置。
    修改后的测试用例代码示例:
@Test
void whenGetReleaseNotesAppVersionWithNoExistingCodeThenNotFoundInJsonFormat() throws Exception {
    this.mvc.perform(get(
            NEWER_RELEASES_PATH_UPDATE_CONFIG + "/"
                    + "6.0.0" + "/notes")
                        .header(AUTH_HEADER, AUTH_TOKEN_SRVCGERETDESAX)
                        .locale(Locale.ENGLISH)
                        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isNotFound())
        // 替换为兼容匹配方法
        .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath(
                "$.code", is(ApiErrorCode.RELEASE_NOTES_NOT_FOUND.getCode())));
}
  • 方案2:全局配置测试环境移除JSON响应的默认charset
    如果不想修改所有测试用例的断言,可以通过配置消息转换器,让测试环境的JSON响应和生产环境一致,不带charset参数:
  1. 新增测试专用的Web配置类:
@TestConfiguration
public class TestMvcConfig implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.stream()
            .filter(MappingJackson2HttpMessageConverter.class::isInstance)
            .map(MappingJackson2HttpMessageConverter.class::cast)
            .forEach(converter -> converter.setDefaultCharset(null));
    }
}
  1. 将配置类加入测试类的启动上下文:
    修改测试类的@SpringBootTest注解,把配置类加入classes属性:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {
        Application.class, TestMvcConfig.class })

配置生效后,所有MockMvc返回的JSON响应ContentType都会自动去掉;charset=UTF-8后缀,原有断言不需要修改即可正常运行。

  • 方案3:临时适配字符串匹配(不推荐,仅应急使用)
    如果需要快速验证测试逻辑,也可以直接断言ContentType前缀匹配:
.andExpect(content().string(containsString("application/json")))

这种方法硬编码了匹配规则,后续如果框架默认配置变更还要二次修改,不建议长期使用。

内容的提问来源于stack exchange,提问作者dragonalvaro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 16:06:08