WireMock是一個HTTP模擬服務器,其核心是Web服務器,可以準備好為特定請求(存根)提供預設響應,并捕獲傳入的請求,以便以后檢查它們(驗證)。當在開發接口時,我們的接口依賴于第三方接口的返回,但第三方接口未開發完成時,我們可以用WireMock來模擬真實的接口服務進行數據返回。又例如, 前端與后端分開開發時,前端依賴于后端接口,后端接口未開發完時,可以自己mock一個接口來進行頁面開發。
面來說說基于Junit的REST Assured測試來驗證模擬的行為,首先需要在工程里面添加wiremock的jar包。如果下載的java是8.0以上的版本,添加依賴方式如下:
maven:
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-jre8</artifactId>
<version>2.23.2</version>
<scope>test</scope>
</dependency>
gradle:
testCompile "com.github.tomakehurst:wiremock-jre8:2.23.2"
其他版本可以參閱官網 http://wiremock.org/docs/download-and-installation/
下面我們創建一個TestCase類
Rule里定義一個WireMockRule 的對象,不傳值時默認在8080端口上啟動
@Rule public WireMockRule wireMockRule = new WireMockRule();
在8089端口上啟動
@Rule
public WireMockRule wireMockRule = new WireMockRule(8089);
定義一個setupStub方法,用來mock一個接口,模擬接口地址為http://localhost:8089/pingpong,body為<input>PING</input>,返回狀態為200,返回的header是Content-Type=application/xml,返回body為<output>PONG</output>
public void setupStub() {
stubFor(post(urlEqualTo("/pingpong"))
.withRequestBody(matching("<input>PING</input>"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/xml")
.withBody("<output>PONG</output>")));
}
其實轉換過來就是這樣的json格式
{
"request": {
"method": "POST",
"urlPath": "/pingpong",
"body": "<input>PING</input>"
},
"response": {
"status": 200,
"body": "<output>PONG</output>",
"headers": {
"Content-Type": "application/xml"
}
}
}
然后編寫測試案例,調用此方法生成一個模擬api,使用REST Assured的given when then方式,請求http://localhost:8089/pingpong地址,斷言響應里的output的內容是否是PONG
@Test
public void testPingPongPositive() {
setupStub();
given().
body("<input>PING</input>").
when().
post("http://localhost:8089/pingpong").
then().
assertThat().
statusCode(200).
and().
assertThat().body("output", org.hamcrest.Matchers.equalTo("PONG"));
}
當我們不依賴于JUnit時,我們可以通過這種方式啟動wiremock
WireMockServer wireMockServer = new WireMockServer(options().port(8089)); //No-args constructor will start on port 8080, no HTTPS wireMockServer.start(); // Sometime later wireMockServer.stop();
如果是手動測試,我們仍然可以使用wiremock模擬api服務,這時我們可以單獨下wiremock的jar包,
http://wiremock.org/docs/running-standalone/,下載后進入安裝jar包的路徑啟動wiremock
java -jar wiremock-standalone-2.1.10.jar(注意版本)
<meta charset="utf-8">
啟動后會生成2個文件夾,__files和mappings。mappings文件夾里的內容可以理解為定義請求的地方,__files主要配合mappings使用,可以理解成存放response請求body的地方,在request中設置響應體文件名稱,服務會對應找到__files下的這個文件作為response返回。
如這就是mappings下的一個json文件
{
"request": {
"method": "Get",
"urlPath": "/pingpong"
},
"response": {
"status": 200,
"bodyFileName": "abc.json",
"headers": {
"Content-Type": "application/xml"
}
}
}
在__files下創建abc.json文件
{
"equalToJson" : "{ "name": "qq" }",
"jsonCompareMode": "LENIENT"
}
在瀏覽器里打開http://localhost:8080/pingpong(8080是默認端口),可以看到返回如下內容:
{
"status": 200,
"bodyFileName": {
{
"equalToJson" : "{ "name": "qq" }",
"jsonCompareMode": "LENIENT"
}
}
"headers": {
"Content-Type": "application/xml"
}
}
注:每次修改為mapping里的文件后需重啟wiremock,__files里的修改不需要