MockMvc 的默认行为
MockMvc 默认使用 ISO-8859-1 解码响应,而服务端实际返回 UTF-8 编码数据
。
Postman 无乱码是因浏览器自动识别编码,但 MockMvc 需显式配置。
过滤器失效场景
Spring 的 CharacterEncodingFilter 默认只对 POST 请求生效,对 GET 请求无效
。
测试环境需手动强制覆盖编码设置。
解决方案一:
在测试代码中强制覆盖编码设置。(注释代码部分)
解决方案二:
添加测试配置文件,指定编码
在test的resources中添加application.properties配置文件,添加配置
server.servlet.encoding.force=true
server.servlet.encoding.charset=UTF-8
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Locale;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;@SpringBootTest
@AutoConfigureMockMvc
public class PlateControllerTest {private static final Logger logger = LoggerFactory.getLogger(PlateControllerTest.class);@Autowiredprivate MockMvc mockMvc;@Testvoid testgetAAA() throws Exception {// 发送 GET 请求到 /plate/getAAA 接口,传入 plateId 参数MvcResult result = mockMvc.perform(get("/plate/getAAA").param("plateId", "1234567")//.characterEncoding("UTF-8")).andExpect(status().isOk()) // 验证 HTTP 200.andExpect(jsonPath("$.data").exists()) // 验证响应包含 data 字段.andReturn(); // 获取返回结果// 打印接口返回结果//String responseContent = result.getResponse().getContentAsString(StandardCharsets.UTF_8);String responseContent = result.getResponse().getContentAsString();logger.info("getAAA接口返回结果: {}", responseContent);}
}