一.moco簡介
在開發過程中,後端接口沒開發完成,測試不能寫接口用例,前端不能寫好相關頁面?
在UI自動化測試裏,後端返回的數據發生改變,導致斷言失敗?
有mock技術前端頁面的調試以及接口測試用例的設計進度不用等待後端。可以採用mock技術,UI測試不再受後端的影響,後端則採用接口自動化驗證數據的正確。
Moco 是一個搭建模擬服務器的工具,其支持 API 和獨立運行兩種方式,前者通常是在 junit 等測試框架中使用,後者則是通過運行一個 jar 包開啓服務。以下總結作爲服務的使用。
二.第一個demo
1.jar包下載 (github上搜moco看源碼)
http://repo1.maven.org/maven2/com/github/dreamhead/moco-runner/0.12.0/
下載moco-runner-0.12.0-standalone.jar
2.寫請求與響應數據:firstdemo.json
[
{
"description":"第一個mock例子",
"request":{
"uri":"/demo"
},
"response":{
"text":"第一個moco框架demo"
}
}
]
3.啓動服務
java -jar ./moco-runner-0.12.0-standalone.jar http -p 5812 -c firstdemo.json
4.啓動成功後,本地瀏覽器或接口工具(Jmeter,postman等)訪問localhost:5812/demo測試接口數據
三.json文件的編寫
1.get請求示例:
[
{
"description":"模擬一個沒有參數get請求",
"request":{
"uri":"/getdemo",
"method":"get"
},
"response":{
"text":"這是一個沒有參數的get請求"
}
},
{
"description":"這是一個帶參數get請求",
"request":{
"uri":"/getdemo2",
"method":"get",
"queries":{
"name":"huhansan",
"sex":"2"
}
},
"response":{
"text":"我胡漢三又回來啦!!!!"
}
}
]
2.模擬一個post請求。使用forms,json傳參[
{
"description":"模擬一個post請求",
"request":{
"method":"post",
"uri":"/postdemo2",
"forms":{
"name":"huhansan",
"sex":"2"
}
},
"response":{
"text":"我胡漢三用Post帶着參數又回來了"
}
}
]
注意:(1)json格式的傳參不能以表格的形式提交,需要寫到body裏,否則400,請求錯誤(隨意截圖)
3.帶cookies的請求示例
[
{
"description":"get請求必須帶cookie",
"request":{
"uri":"/get/withcookies",
"method":"get",
"cookies":{
"login":"true"
}
},
"response":{
"text":"with cookies"
}
},
{
"description":"帶cookie的post請求",
"request":{
"uri":"/post/withcookies",
"method":"post",
"cookies":{
"login":"true"
},
"json":{
"name":"huanhansan",
"sex":"2"
}
},
"response":{
"status":200,
"json":{
"name":"huhansan",
"age":"20",
"home":"casa residency"
}
}
}
]
使用Jmeter發起請求
4.帶header的請求
[
{
"description":"這是一個帶header信息的post請求",
"request":{
"uri":"/post/with/headers",
"method":"post",
"headers":{
"content-type":"application/json"
},
"json":{
"name":"wanglaosi",
"sex":"woman"
}
},
"response":{
"json":{
"wanglaosi":"success",
"status":"1"
}
}
}
]
Jmeter header示例:
5.請求重定向
[
{
"description":"重定向到百度",
"request":{
"uri":"/redirectmemo"
},
"redirectTo":"http://www.baidu.com"
},
{
"description":"重定向原始請求",
"request":{
"uri":"/redirectnew"
},
"redirectTo":"/wangjieinfo"
},
{
"description":"目標頁面",
"request":{
"uri":"/wangjieinfo"
},
"response":{
"json":{
"name":"wangjie",
"sex":"man",
"status":0
}
}
}
]