wiremock 简介
WireMock是一个开源的测试工具,支持HTTP响应存根、请求验证、代理/拦截、记录和回放。最直接的用法:
- 为Web/移动应用构建Mock Service
- 快速创建Web API原型
- 模拟Web Service中错误返回
- 录制HTTP请求和回放
生成mock API的方式
生成mock api有两种方式:一种是新建mapping文件,另一种是通过wiremock的api. 其中第一种可以永久保存下来,第二种是暂时生成API,待下次build container后,会被清除. 下面详细介绍一下两种方式:
新建Mapping文件生成mock API
一个Mock的api对应一个json文件,放在mapping/下,文件格式如下:
{"request": {"url": "/QueryPWIDByLoginname","method": "POST","bodyPatterns": [{"equalToJson": "{ \"loginName\":\"17317920860\"}","ignoreArrayOrder": true,"ignoreExtraElements": true}]},"response": {"status": 200,"body": "{\"code\":\"0\",\"data\":{\"AccountID\":\"\",\"LoginNameType\":\"2\",\"LoginStatus\":\"1\",\"PWID\":\"300111000156276629\",\"PWIDType\":\"wanda\",\"Status\":\"1\",\"SysFrom\":\"wandacloud\"},\"msg\":\"success\"}","headers": {"Content-Type": "application/json; charset=utf-8","Date": "Fri, 18 Aug 2017 07:05:05 GMT"}}}
mapping文件可以手动写,也可以通过wiremock的record功能生成.
record 功能生成mapping
wiremock Server提供了record UI, 访问地址: :31703/__admin/recorder/
下面以登录注册模块QueryPWIDByLoginname功能为例,打开record UI, 需要mock的URL填入,:30303,点击 Record按钮. 之后发向:30303的请求,可以用:31703来代理例如,应发送请求:访问:curl -X POST "http://10.214.169.111:31703/QueryPWIDByLoginname" -H "accept: application/vnd.response+json" -H "content-type: application/json" -d "{ \"loginName\": \"17317920860\"}"
返回:
{"code":"0","data":{"AccountID":"","LoginNameType":"2","LoginStatus":"1","PWID":"300111000156276629","PWIDType":"wanda","Status":"1","SysFrom":"wandacloud"},"msg":"success"}
点击Stop按钮,结果如下:
2.调用wiremock的api获取录制内容:使用curl/浏览器等方式获取::31703/__admin/mappings
3.将request和response部分拷贝到一个mapping目录下的一个新json文件, 上传git,完成.
使用wiremock admin rest api生成mock API
/__admin/mappings
POST :31703/__admin/mappingsbody:{"request": {"method": "GET","url": "/fromAPI"},"response": {"status": 200,"body": "Hello world - API!","headers": {"Content-Type": "text/plain"}}}