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();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM