一、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來模拟請求資料。