?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);}
}