一、moco简介
moco框架是github上的一个开源项目,可模拟http,https,Socket协议。
mock测试就是在测试过程中,对于某些不容易构造 或者 不容易获取的对象 又或者 开发还未完成开发的功能实现,用一个虚拟的对象来创建以便测试的测试方法。
二、moco框架的下载及启动
下载:https://github.com/dreamhead/moco
这里我的moco目录结构是在同一文件夹下,这样的:
启动:java -jar moco-runner-1.0.0-standalone.jar http -p 2222 -c get_data.json (启动协议为http的mock服务,服务端口2222)
三、模拟GET请求
以下是模拟get请求已经写好的要模拟数据,包括请求uri,method,参数,响应内容
[
{
"description":"不带参数的get请求",
"request":{
"uri":"/withGetDemo",
"method":"get"
},
"response":{
"text":"这是不带参数的get请求"
}
},
{
"description":"带参数的get请求,p1,p2分别的参数1,参数2,名称可随便起,个数也可随便加",
"request":{
"uri":"/wihtGetDemobyParam",
"method":"get",
"queries":{
"p1":"hh",
"p2":"good"
}
},
"response":{
"text":"这是带参数的get请求"
}
}
]
这里我用浏览器模拟第一个get请求,得到的响应如下:
这里我用postman模拟第二个带有请求参数的get请求,得到的响应如下:
四、模拟POST请求
以下为post请求的几种请求方式:
1、不带参数的post请求
2、带参数的post请求
3、带cookie的post请求
4、带header的post请求
模拟的返回响应数据如下
[
{
"description":"不带参数的post请求",
"request":{
"uri":"/postDemo",
"method":"post"
},
"response":{
"text":"这是不带参数的post请求"
}
},
{
"description":"带参数的post请求",
"request":{
"uri":"/postDemoWithParam",
"method":"post",
"forms":{
"param1":"one",
"param2":"two"
}
},
"response":{
"json":{"name":"han","age":30,"address":"beijing daxing"}
}
},
{
"description":"带cookie的Post请求",
"request":{
"uri":"/postDemoWithCookies",
"method":"post",
"cookies":{
"login":"true"
},
"json":{
"name":"hi",
"age":"3"
}
},
"response":{
"status":"200",
"json":{
"name":"success",
"status":"1"
}
}
},
{
"description":"带header的post请求",
"request":{
"uri":"/withHeader",
"method":"post",
"headers":{
"content-type":"application/json"
},
"json":{
"name":"xiaoming",
"age":"18"
}
},
"response":{
"json":{
"message":"success",
"status":"1"
}
}
}
]
以下为用postman模拟请求
2、带参数的post请求(这里用的application/x-www-form-urlencoded)
3、带cookie的post请求(虽然模拟请求中写的是cookies,但是在请求的时候一定要写成cookie,不要加“s”)
综上,在mock数据时不妨试试moco来模拟请求数据。