最近研究一下httpmock,用到了moco框架,很简单粗暴,记录一下。
github:GitHub - dreamhead/moco: Easy Setup Stub Server 有详细的文档可以参考
moco的优点:
1.只需要简单的配置request、response等即可满足要求,支持http、https、socket。可以说是非常的灵活性。
2.支持在request 中设置 Headers , Cookies , StatusCode等。
3.对GET、POST、PUT、DELETE等请求方式均支持,很适合web开发。
4.无需环境配置,有java环境即可。
5.修改配置后,立刻生效。只需要维护接口,也就是契约即可。
6.对可能用到的数据格式都支持,如json、text、xml、file等。
7.还能与其他工具集成,如Junit、Maven、Gradle等。
moco的缺点:
- 没有转发功能,如果遇到没有匹配的请求进来接口会400,所以它对单接口测试十分方便;或者可以在压测中mock外部依赖。
开始搞起
- 下载jar包:Standalone Moco Runner
- 写一个启动的脚本,方便使用 start-moco.sh:
启动一个http服务,方便后端接口调用
nohup java -jar moco-runner-0.11.0-standalone.jar http -p 12306 -c match_uri.json >>$PWD/moco.log 2>&1 &
#!/bin/bash
source /etc/profile
PID=$(ps -ef |grep -w 'moco-runner'|grep -v 'grep' |awk {'print $2'})
USAGE()
{
echo "usage: $0 start|stop|status"
}
if [ $# -lt 1 ]; then
USAGE
exit -1
fi
START(){
if [ "$PID" == "" ];
then
echo "starting moco-runner ..."
nohup java -jar moco-runner-0.11.0-standalone.jar http -p 12306 -c match_uri.json >>$PWD/moco.log 2>&1 &
else
echo "moco-runner is running,please stop it first!!!"
fi
}
STATUS(){
if [ "$PID" == "" ];
then
echo "moco-runner is stopped!!!"
else
echo "moco-runner is running!!!"
fi
}
STOP(){
if [ "$PID" == "" ];
then
echo "moco-runner is stopped!!!"
else
echo "stopping moco-runner ..."
kill -9 $PID
fi
}
if [ $1 == "start" ];
then
START
elif [ $1 == "stop" ];
then
STOP
else
STATUS
fi
3. 配置mock入口,json格式的文件 match_uri.json :
[{
"request" :
{
"uri" : "/index/hello"
},
"response" :
{
"file" : "mocks/hello.txt"
}
}
]
4.配置mock的文件:hello.txt
{
"status":1,
"error":"200",
"msg":"服务调用成功",
"data":"您好"
}
5.最后一步:启动mock
sh start-moco.sh start