Moco 是一个搭建模拟服务器的工具,其支持 API 和独立运行两种方式,前者通常是在 junit 、testng等测试框架中使用,后者则是通过运行一个 jar 包开启服务
在maven中央仓库中,moco有三个版本,分别是moco-core、moco-runner、moco-junit。如果需要在junit等测试框架中使用,则需要同时引进这三个包。如果是独立运行的方式,则只需要下载moco-runner-standalone这个包到本地就可以了,这个包并不是maven中央仓库中的moco-runner,而是moco-runner-standalone,下载地址为:下载地址,下载带有standalone标识的jar包。
moco的github地址为:github,可以在自述文件中点击链接Standalone Moco Runner下载最新的standalone版本的jar包。
下面分别介绍独立运行和api两种方式运行。
下载moco-runner到本地。
准备json配置文件。
启动服务,命令格式如下:
java -jar jar包的路径 http -p 运行端口 -c 要运行的json配置文件(可以包含路径)
get请求json配置文件示例:
[{"description": "一个简单的get请求","request": {"method": "get","uri": "/login"},"response": {"text": "我是login get method","headers":{"Content-Type":"text/html;charset=utf-8"}}},{"description": "带参数的get请求,p1和p2是两个参数","request": {"method": "get","uri": "/reg","queries": {"p1": "v1","p2": "v2"}},"response": {"text": "带参数的get请求","headers":{"Content-Type":"text/html;charset=utf-8"}}},{"description": "get请求返回json类型数据","request": {"method": "get","uri": "/login_json"},"response": {"json": {"key":"value","请求方式是get":"响应结果为json类型"},"headers": {"Content-Type": "application/json;charset=utf-8"}}}
]
post请求json配置文件示例:
[{"description": "post请求,请求参数为json格式,响应格式为json","request": {"method": "post","uri": "/post_json","json": {"login_status": "successful"}},"response": {"json": {"login": "ok"},"headers": {"Content-Type": "application/json;charset=utf-8"}}},{"description": "post请求,请求及响应都为json,并且请求带cookies","request": {"method": "post","uri": "/post_cookie","json": {"login_status": "successful"},"cookies":{"user_id":"xsdaqawea"}},"response": {"json": {"login": "ok"},"headers": {"Content-Type": "application/json;charset=utf-8"}}},{"description": "post请求,请求及响应都为json,并且请求带cookies和headers","request": {"method": "post","uri": "/post_cookie_headers","json": {"login_status": "successful"},"cookies": {"user_id": "xsdaqawea"},"headers":{"Content-Type":"application/json"}},"response": {"json": {"login": "ok"},"headers": {"Content-Type": "application/json;charset=utf-8"}}},{"description": "post请求,请求和响应为form,入参是form形式,返回是json数据","request": {"method": "post","uri": "/login_form","forms": {"username": "zhangshan","password": "123456"},"headers": {"content-type": "application/x-www-form-urlencoded"}},"response": {"json": {"error_code": 0,"reason": "successed","username": "zhangshan","checkstatus": "on"},"status": 200}}
]
注意:
post请求中:
headers:请求头,根据是form还是json格式的请求来填写
from格式:“content-type”: “application/x-www-form-urlencoded”
json格式:“content-type”: “application/json”
请求参数格式以及数据,对应headers的content-type
form格式关键字为forms
json格式关键字为json
重定向json配置文件示例:
[{"description":"重定向到指定网站","request":{"method":"get","uri":"/login_redirect"},"redirectTo":"https://www.baidu.com"}
]
配置一组json配置文件。
[{"include":"get.json"},{"include":"post.json"},{"include":"redirect.json"}
]
这种方式的启动命令与前面的不太一样,具体格式如下:
java -jar jar包的路径 http -p 运行端口 -g 要运行的组配置文件(可以包含路径)
可以看到,区别就是配置文件前面的命令变成了-g。
此种方式形式还不清晰,后面用到了再具体描述。