About
mock除了用在单元测试过程中,还有一个用途,当前端开发在开发页面的时候,需要服务端提供API接口。
此时服务端没开发完成,或者说没搭建测试环境,这个时候前端开发会自己mock一个api服务端,自己给自己提供调用接口的返回数据。
moco框架用途就是开发在开发的过程中,需要依赖一部分的接口,但是对方没有提供或者环境等等情况。
moco框架支持API和独立运行两种方式,API的方式通常运行在Junit等java的测试框架中,而独立的运行方式是通过jar包开启服务,可以模拟HTTP,HTTPS,socket协议。这里介绍标准用法。
更多使用方法参考:https://github.com/dreamhead/moco/blob/master/moco-doc/usage.md
另外,jar包的运行依赖于java虚拟机,这里我们还需要安装java的JDK:
- java for windows:https://www.cnblogs.com/sundawei7/p/11956103.html
- java for Mac OS:https://www.cnblogs.com/sundawei7/p/11956203.html
- java for centos:https://www.cnblogs.com/sundawei7/p/11956295.html
jar包下载
- github官网:https://github.com/dreamhead/moco
- moco-runner:http://central.maven.org/maven2/com/github/dreamhead/moco-runner/1.0.0/moco-runner-1.0.0-standalone.jar
这个jar包只提供服务,我们还需要配置文件,配置我们自己定义的规则信息。
将配置文件和下载的jar放在同一目录下。配置规则的文件,是json类型的文件,比如叫做configure.json文件。记得,每次修改了配置文件,就要重新运行jar包。
M:\test\moco-runner\ ├─moco-runner-1.0.0-standalone.jar └─configure.json
如何运行:
M:\tests\moco-runner>java -jar moco-runner-0.12.0-standalone.jar start -p 8888 -c config.json
访问:
http://127.0.0.1:8888/login
快速上手
再次强调:
- 配置文件修改后,就要重新运行jar包。
- 配置文件为json类型,对格式的要求比较高,要注意点!
开搞!
get请求
configure.json:
[ { "description": "一个简单的get请求", "request": { "method": "get", "uri": "/login" }, "response": { "text": "我是login get method", "headers":{ "Content-Type":"text/html;charset=gbk" } } }, { "description": "带参数的get请求,p1和p2是两个参数", "request": { "method": "get", "uri": "/reg", "queries": { "p1": "v1", "p2": "v2" } }, "response": { "text": "带参数的get请求", "headers":{ "Content-Type":"text/html;charset=gbk" } } }, { "description": "get请求返回json类型数据", "request": { "method": "get", "uri": "/login_json" }, "response": { "json": { "key":"value", "请求方式是get":"相应结果为json类型" }, "headers": { "Content-Type": "application/json;charset=gbk" } } } ]