package com.tzld.supply.proxy.controller; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.util.EntityUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; public class ProxyControllerTest { private MockMvc mockMvc; private HttpClient httpClient; private ProxyController proxyController; @BeforeEach public void setup() { httpClient = mock(HttpClient.class); proxyController = new ProxyController(httpClient); mockMvc = MockMvcBuilders.standaloneSetup(proxyController).build(); } @Test public void testProxyPostWithBodyEncoding() throws Exception { String body = "{\"name\":\"测试\"}"; String targetUrl = "http://example.com/api"; // Mock response HttpResponse response = mock(HttpResponse.class); StatusLine statusLine = mock(StatusLine.class); HttpEntity responseEntity = mock(HttpEntity.class); when(httpClient.execute(any(HttpRequestBase.class))).thenReturn(response); when(response.getStatusLine()).thenReturn(statusLine); when(statusLine.getStatusCode()).thenReturn(200); when(response.getEntity()).thenReturn(responseEntity); when(responseEntity.getContent()).thenReturn(new ByteArrayInputStream("OK".getBytes())); mockMvc.perform(post("/proxy/test") .header("Target-URL", targetUrl) .contentType(MediaType.APPLICATION_JSON) .content(body)) .andExpect(status().isOk()); ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(HttpRequestBase.class); verify(httpClient).execute(argumentCaptor.capture()); HttpRequestBase capturedRequest = argumentCaptor.getValue(); if (capturedRequest instanceof HttpPost) { HttpPost httpPost = (HttpPost) capturedRequest; HttpEntity entity = httpPost.getEntity(); // StringEntity default encoding is ISO-8859-1 // We expect this to fail if the controller doesn't handle encoding correctly String capturedBody = EntityUtils.toString(entity, StandardCharsets.UTF_8); assertEquals(body, capturedBody, "Body content should match, checking for encoding issues"); } } }