简单的httpmock-MOCO

最近研究一下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的缺点:

  1. 没有转发功能,如果遇到没有匹配的请求进来接口会400,所以它对单接口测试十分方便;或者可以在压测中mock外部依赖。

开始搞起 

  1. 下载jar包:Standalone Moco Runner 
  2. 写一个启动的脚本,方便使用 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

验证一下:

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值