強(qiáng)大的mock工具-wiremock
安裝啟動(dòng)(docker)
使用容器創(chuàng)建服務(wù)
要掛載當(dāng)前目錄,請(qǐng)使用例如:-v $PWD:/Users/fnngj/zhpro/wiremock
啟動(dòng)成功
創(chuàng)建mock接口
創(chuàng)建一個(gè)簡(jiǎn)單的 GET接口
查看創(chuàng)建的mock接口
訪問(wèn):http://127.0.0.1:8090/__admin/mappings

調(diào)用創(chuàng)建的 mock 接口(瀏覽器調(diào)用)

請(qǐng)求匹配
wiremock 除了一般的 請(qǐng)求方法 + URL 之外,支持各種類(lèi)型請(qǐng)求匹配。
可以使用以下請(qǐng)求屬性:
URL
HTTP Method
Query parameters
Headers
Basic authentication (a special case of header matching)
Cookies
Request body
Multipart/form-data
例如設(shè)置匹配 請(qǐng)求中的某個(gè)字段的值,如果出現(xiàn)了就匹配這個(gè)mock。
要求請(qǐng)求的結(jié)構(gòu)體必須出現(xiàn)使用下面數(shù)據(jù),才能匹配到這個(gè) Mock:
驗(yàn)證請(qǐng)求匹配

更多用法:https://wiremock.org/docs/request-matching/
響應(yīng)模板
response 返回,支持動(dòng)態(tài)模板。支持從請(qǐng)求中提取數(shù)據(jù)放到 響應(yīng)數(shù)據(jù)中。
以下請(qǐng)求屬性是可用的:
request.url
?- URL path and queryrequest.path
?- URL pathrequest.pathSegments.[<n>]
?- URL path segment (zero indexed) e.g.?request.pathSegments.[2]
request.query.<key>
?- First value of a query parameter e.g.?request.query.search
request.query.<key>.[<n>]
?- nth value of a query parameter (zero indexed) e.g.?request.query.search.[5]
request.method
?- request method e.g.?POST
request.host
?- hostname part of the URL e.g.?my.example.com
request.port
?- port number e.g.?8080
request.scheme
?- protocol part of the URL e.g.?https
request.baseUrl
?- URL up to the start of the path e.g.?https://my.example.com:8080
request.headers.<key>
?- First value of a request header e.g.?request.headers.X-Request-Id
request.headers.[<key>]
?- Header with awkward characters e.g.?request.headers.[$?blah]
request.headers.<key>.[<n>]
?- nth value of a header (zero indexed) e.g.?request.headers.
ManyThings.[1]request.cookies.<key>
?- First value of a request cookie e.g.?request.cookies.JSESSIONID
request.cookies.<key>.[<n>]
?- nth value of a request cookie e.g.?request.cookies.JSESSIONID.[2]
request.body
?- Request body text (avoid for non-text bodies)
例如 從請(qǐng)求體的 body 中提取 name 填充到 response 中。
要求請(qǐng)求的結(jié)構(gòu)體必須出現(xiàn)使用下面數(shù)據(jù),這個(gè) Mock 才能提取到數(shù)據(jù):
驗(yàn)證響應(yīng)提取匹配

更多用法:https://wiremock.org/docs/response-templating/
模擬故障
有時(shí)希望模擬接口返回 HTTP 狀態(tài)碼 非 200, 或者 延遲返回。wiremock 同樣可以輕松應(yīng)對(duì)。
例如 response 模擬 HTTP 狀態(tài)碼 501, 并且延遲 2s 返回。
驗(yàn)證響應(yīng)提取匹配

更多用法:https://wiremock.org/docs/simulating-faults/
結(jié)束
WireMock 還有好多功能,我們最近在調(diào)研mock工具,以上這些特性都是我們需要用到的。發(fā)現(xiàn) wiremock 是為數(shù)不多mock 能力比較強(qiáng)大,而且在持續(xù)更新的工具。
除此之外,wireMock 還提供各種語(yǔ)言的 SDK,也就是說(shuō)我們可以在編程語(yǔ)言中使用 wiremock。而且,還有 wiremock 的云平臺(tái),可以通過(guò)web界面創(chuàng)建 mock 服務(wù)。