
前段时间介绍了Mock基本知识以及市面上常见的Mock工具(Mock工具介绍),今天重点介绍小编在测试过程当中使用的Mock工具-Moco。git
1.Mock简便性:简单上手,尽可能减小学习成本。正则表达式
2.项目开源(https://github.com/dreamhead/moco)数据库
3.部署容易:Moco的运行很是简单,只须要一行命令便可。json
4.Mock参数配置:Moco能够将须要返回的具体结果写在Json文件中;YApi能够经过mockjs、json-schema进行数据Mock,扩展性更好,但指定返回结果成本较高。服务器
Moco自己支持API和独立运行两种方式。经过使用API,开发人员能够在JUnit、JBehave等测试测试框架里使用Moco,极大程度地下降了集成点测试的复杂度。markdown
Moco能够提供如下服务:cookie
HTTP APIs
Socket APIs
REST API
Moco会根据一些配置,启动一个真正的HTTP服务(会监听本地的某个端口)。当发起请求知足一个条件时,它就给回复一个应答。Moco的底层没有依赖于像Servlet这样的重型框架,而是基于一个叫Netty网络应用框架直接编写的,这样一来,绕过了复杂的应用服务器,因此,它的速度是极快的。
Moco独立运行时所需准备的有:
Moco的运行很是简单,只须要一行命令便可
如在命令行中运行:
java -jar <path-to-moco-runner> http -p <monitor-port> -c < configuration -file>
<path-to-moco-runner>:moco-runner- 0.11 . 0 -standalone.jar包的路径
<monitor-port>:http服务监听的端口
<configuration -file>:配置文件路径
|

1.配置文件添加注释
[
{
"description" : "这是一个注释行,对该接口进行描述" ,
"request" :{
"uri" : "/sogou"
},
"response" : {
"file" : "sogou.response"
}
}
]
|
2.约定接口Uri
能够在uri中使用正则表达式进行匹配
其中request这个key为请求相关内容,response为返回的相关内容
[
{
"description" : "request中uri必须是/sogou,才能匹配该接口" ,
"request" :{
"uri" : "/sogou"
},
"response" : {
"file" : "sogou.response"
}
}
]
|
3.约定请求参数
[
{
"description" : "request中必须包含参数param=test,才能匹配该接口" ,
"request" :{
"queries" :{
"param" : "test"
}
},
"response" : {
"file" : "sogou.response"
}
}
]
|
4.约定请求方法
[
{
"description" : "request必须是get请求,才能匹配此接口,除此外还支持post|put|delete|Head方法" ,
"request" :{
"method" : "get" ,
},
"response" : {
"file" : "sogou.response"
}
}
]
|
5.约定HTTP版本
[
{
"description" : "request必须是HTTP/1.0,才能匹配此接口" ,
"request" :{
"version" : "HTTP/1.0" ,
},
"response" : {
"file" : "sogou.response"
}
}
]
|
6.约定HTTP请求头部
[
{
"description" : "request必须包含头部:application/json,才能匹配此接口" ,
"request" :{
"method" : "get" ,
"headers" : {
"content-type" : "application/json"
}
},
"response" : {
"file" : "sogou.response"
}
}
]
|
7.约定Cookie
[
{
"description" : "request必须包含cookies:login-true,才能匹配此接口" ,
"request" :{
"method" : "get" ,
"cookies" : {
"login" : "true"
}
},
"response" : {
"file" : "sogou.response"
}
}
]
|
8.约定请求Form
[
{
"description" : "request必须包含表单:name-sogou,才能匹配此接口" ,
"request" :{
"method" : "get" ,
"forms" : {
"name" : "sogou"
}
},
"response" : {
"file" : "sogou.response"
}
}
]
|
9.设置Response Content
[
{
"description" : "接口匹配后,response返回文件sogou.response,文件编码为GBK" ,
"request" :{
"method" : "get"
},
"response" : {
"file" : "sogou.response" ,
"charset" : "GBK"
}
}
]
|
10.设置Response 状态码
[
{
"description" : "接口匹配后,response返回状态码500" ,
"request" :{
"method" : "get"
},
"response" : {
"status" : " 500"
}
}
]
|
11.设置重定向
[
{
"description" : "接口匹配后,返回重定向地址" ,
"request" :{
"uri" : "/sogou"
},
"redirectTo" : "www.sogou.com"
}
]
|
Moco的使用很简单,配置也很方便,目前更是提供了http、rest、socket服务。可是也仅仅是能stub出接口,模拟出简单的场景。若是接收到请求后须要作一些处理,如需查询数据库、进行运算、或者一些复杂的操做,就无能为力了。因此是否选用Moco,就取决于开发者是否只是须要一个简单的模拟服务器。
搜狗测试微信号:Qa_xiaoming

搜狗测试QQ粉丝群:459645679
