MockServer 入门


忽略元数据末回到原数据开始处

MockServer介绍及文档 借鉴公司的文档

  1. http://mock-server.com
  2. github:https://github.com/jamesdbloom/mockserver

MockServer can:

  • return a "mock" response when a request matches an expectation
  • forward a request when the request matches an expectation (i.e. a dynamic port forwarding proxy)
  • execute a callback when a request matches an expectation, allowing the response to be created dynamically
  • verify requests have been sent (i.e. as a test assertion)

设置pom

<dependency>
    <groupId>org.mock-server</groupId>
    <artifactId>mockserver-netty</artifactId>
    <version>3.10.1</version>
</dependency>

 

如何在java里启动一个mockserver

  1. import mockserver相关包

import static org.mockserver.integration.ClientAndServer.startClientAndServer;

import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;

import static org.mockserver.model.HttpForward.forward;
import static org.mockserver.model.HttpForward.Scheme;

import static org.mockserver.model.HttpCallback.callback;

2. 启动mockserver

ClientAndServer mockServer = startClientAndServer(1080);

 

2.1 设置mockserver response


mockServer
.when(
request()
.withMethod("POST")
.withPath(this.basePath)
.withBody("{username: 'foo', password: 'bar'}")
)
.respond(
response()
.withStatusCode(200)
.withCookie(
"sessionId", "2By8LOhBmaW5nZXJwcmludCIlMDAzMW"
)
.withHeaders(
new Header("Content-Type", "application/json; charset=utf-8"),
new Header("Cache-Control", "public, max-age=86400")
)
.withBody("{ \"apply_id\": \"000001\", \"overdued\": \"Y\" }")
// .withBody("{ \"message\": \"incorrect username and password combination\" }")
);

2.2 设置mockserver forward

mockServer
.when(
request()
.withMethod("POST")
.withPath(this.basePath)
.withBody("{username: 'foo', password: 'bar'}")
)
.forward(
forward()
.withHost("http://10.226.3.3")
.withPort(12345)
.withScheme(Scheme.HTTPS)
);

2.3设置mockserver callback

mockServer
.when(
request()
.withMethod("POST")
.withPath(this.basePath)
.withBody("{username: 'foo', password: 'bar'}")
)
.callback(
callback()
.withCallbackClass("callbackclassname")
);




2.4 停止mockserver

mockServer.stop();

posted @ 2017-05-03 17:13  托马斯布莱克  阅读(3267)  评论(0编辑  收藏  举报