简介
实际开发中,如果遇到后端接口开发跟不上前端开发,或者前端开发需要测试模拟一些服务端返回的边界测试参数等情况,可以用到moco工具模拟服务端接口并且返回自己想要的参数。
Moco 是一个搭建模拟服务器的工具,其支持 API 和独立运行两种方式,前者通常是在 junit 等测试框架中使用,后者则是通过运行一个 jar 包开启服务。接下来讲的是独立使用的使用过程。
1,下载moc jar包
下载路径:https://repo1.maven.org/maven2/com/github/dreamhead/moco-runner/
这里下载的是独立运行的moco-runner-1.1.0-standalone.jar
2,创建config.json文件
下载完后需要创建配置文件config.json
如果想改变返回的参数,可以在这里直接修改
[{
"request": {
"method": "get",
"uri": "/getlikheatenum",
"queries": {
"channelid": "1024"
}
},
"response": {
"json": {
"data": {
"heat_degree": 4511,
"like_num": 2685,
"top_users": [
"7981625233425640",
"4857325562408476",
"1004285809743988",
"1548065101238578"
]
},
"count": 0,
"result": 1,
"message": "操作成功",
"time": 1605936061
}
}
},
{
"request": {
"uri": {
"match": "/test/\\w+"
}
},
"response": {
"text": "Hello, Moco"
}
}
]
3,执行命令开启服务
在上面jar包和json文件的同文件夹下打开cmd,执行(这里默认java 环境已经安装了哈):
java -jar moco-runner-1.1.0-standalone.jar http -p 12305 -c config.json
这里的-p 12305指的是请求的端口号是12305,-c config.json指配置的文件也可以是-g全局的。
执行结果如下表示成功:
D:\Work\plan>java -jar moco-runner-1.1.0-standalone.jar http -p 12305 -c config.json
21 十一月 2020 13:15:39 [main] INFO Server is started at 12305
21 十一月 2020 13:15:40 [main] INFO Shutdown port is 50955
21 十一月 2020 13:16:38 [pool-1-thread-4] INFO Request received:
4,使用postman或网页直接验证
可以在postman或者网页输入:http://localhost:12305/getlikheatenum?channelid=1024
看到请求的返回结果:
{
"data": {
"heat_degree": 4511,
"like_num": 2685,
"top_users": [
"7981625233425640",
"4857325562408476",
"1004285809743988",
"1548065101238578"
]
},
"count": 0,
"result": 1,
"message": "操作成功",
"time": 1605936061
}
同时可以在上面打开的cmd里看到模拟服务被请求记录:
21 十一月 2020 15:14:15 [pool-1-thread-100] INFO Request received:
GET /getlikheatenum HTTP/1.1
Cache-Control: no-cache
User-Agent: PostmanRuntime/7.26.8
Connection: keep-alive
Postman-Token: 72ae980f-2526-487f-93b2-da436137892c
Host: localhost:12305
Accept-Encoding: gzip, deflate, br
21 十一月 2020 15:14:15 [pool-1-thread-100] INFO Response return:
HTTP/1.1 200
Content-Length: 195
Content-Type: application/json; charset=gbk
{"data":{"heat_degree":4511,"like_num":2685,"top_users":["7981625233425640","4857325562408476","1004285809743988","1548065101238578"]},"count":0,"result":1,"message":"操作成功","time":1605936061}