看起来,wiremock会覆盖Content-Length头对象。我希望resposne.body()。contentLength()能够读取内容长度。请参阅下面的测试用例:
import com.github.tomakehurst.wiremock.WireMockServer;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import com.github.tomakehurst.wiremock.core.Options;
import com.google.common.net.HttpHeaders;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import org.junit.Assert;
import org.junit.Test;
public class WireMockTest {
@Test
public void wireMockTest() throws IOException{
String route = "/test";
long contentLength = 9;
//Build the mock server
WireMockServer server = new WireMockServer(Options.DYNAMIC_PORT);
server.stubFor(get(route)
.willReturn(aResponse()
.withHeader(HttpHeaders.CONTENT_TYPE, "image/png")
.withHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(contentLength)) //Does not work, gets overwritten with -1 by okhttp (means it's not found)
.withBody("TEST-BODY")
)
);
server.start();
//Hit the server with okHttp
String mockRequestURL = "http://localhost:" + server.port() + route;
okhttp3.Request serverRequest = new okhttp3.Request.Builder().url(mockRequestURL).build();
OkHttpClient client = new OkHttpClient.Builder().build();
Response resposne = client.newCall(serverRequest).execute();
//Verify the content length is not set
Assert.assertEquals("The content length was not read correctly", contentLength, resposne.body().contentLength());
}
}
答案 0 :(得分:0)
当我通过向服务器发布请求添加路由时,我能够让它尊重标题。
@Test
public void wireMockTest() throws IOException{
String route = "/test";
String body = "Hello World!";
//Build the mock server
WireMockServer server = new WireMockServer(Options.DYNAMIC_PORT);
server.start();
//Configure okHttp
OkHttpClient client = new OkHttpClient.Builder().build();
String mockServerURL = "http://localhost:" + server.port();
//Add the route to the server using JSON
okhttp3.Request configRequest = new okhttp3.Request.Builder().url(mockServerURL + "/__admin/mappings")
.post(RequestBody.create(MediaType.parse("application/json"),
"{\n" +
" \"request\": {\n" +
" \"method\": \"GET\",\n" +
" \"url\": \"" +route + "\"" +
" },\n" +
" \"response\": {\n" +
" \"status\": \"200\",\n" +
" \"body\": \""+body+"\",\n" +
" \"headers\": {\n" +
" \"Content-Type\": \"text/plain\",\n" +
" \"Content-Length\": \""+body.length()+"\"\n" +
" }\n" +
" }\n" +
"}")).build();
client.newCall(configRequest).execute();
//Hit the server with okHttp
okhttp3.Request serverRequest = new okhttp3.Request.Builder().url(mockServerURL + route).build();
Response resposne = client.newCall(serverRequest).execute();
//Verify the content length is not set
Assert.assertEquals("The content length was no read correctly", body.length(), resposne.body().contentLength());
}