Maven 引入
org.mock-server
mockserver-netty
5.4.1
org.mock-server
mockserver-client-java
5.4.1
示例一
ClientAndServer 用法
package com.yzy.mock;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.model.Cookie;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
import static org.mockserver.model.Parameter.param;
public class MockServer {
public static void main(String[] args) {
ClientAndServer server = new ClientAndServer(1080);
server.when(
request()
.withMethod("GET")
.withPath("/test")
.withQueryStringParameters(
param("p", "1")
)
).respond(
response()
.withCookie(new Cookie("cKey", "cValue"))
.withBody("test1")
);
server.when(
request()
.withMethod("GET")
.withPath("/test")
.withQueryStringParameters(
param("p", "2")
)
).respond(
response()
.withBody("test2")
);
}
}
启动main方法,打开浏览器,输入http://localhost:1080/test?p=1,页面返回test1,并且成功写入cookie。注意写入的cookie 是Session 级别的,会话关闭将消失。输入http://localhost:1080/test?p=2,页面返回test2,说明MockServer 同时监听的两个匹配都有效。
示例二
MockServerClient 用法
package mock;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Rule;
import org.junit.Test;
import org.mockserver.client.MockServerClient;
import org.mockserver.junit.MockServerRule;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
public class MockServerTest {
@Rule
public MockServerRule server = new MockServerRule(this, 1080);
@Test
public void test() throws IOException {
MockServerClient mockClient = new MockServerClient("localhost", 1080);
String expected = "hello world";
mockClient.when(
request()
.withPath("/hello")
.withMethod("GET")
).respond(
response()
.withStatusCode(200)
.withBody(expected)
);
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://localhost:1080/hello");
CloseableHttpResponse response = client.execute(httpGet);
//验证
InputStream content = response.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(content);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String responseText = bufferedReader.readLine();
assertThat(responseText, equalTo(expected));
}
}
运行test,执行通过。