Mock就是模擬接口的。本文學習Mock的 Moco開源框架。
Moco源碼和jar下載地址: git jar 下載moco-runner-xxxx-standalone.jar
- moco的啟動及第一個demo
Step1: 在項目中創建一個package:moco,並將下載的jar包放在該package下。
Step2:創建一個json文件,格式如下:
[
{
"description":"This is my first mock demo",
"request":{
"uri":"/demo"
},
"response":{
"text":"This is response"
}
}
]
Step3:cmd進入到該package下,運行命令:java -jar ./moco-runner-0.12.0-standalone.jar http -p 8888 -c startup1.json
在命令行中出現,則命令運行成功
29 Apr 2019 14:31:54 [main] INFO Server is started at 8888 29 Apr 2019 14:31:55 [main] INFO Shutdown port is 52901
Step4:打開瀏覽器,輸入 localhost:8888.在瀏覽器上就可以看到我們在json文件中定義的數據。
- Moco框架的http協議get方法的Mock實現
1. 不帶參數的get實現:
[
{
"description":"This is Get request without paramter",
"request":{
"uri":"/getdemo",
"method":"get"
},
"response":{
"text":"This is response for Get request without paramter "
}
}
]
2.帶參數的get實現:
{
"description":"This is Get request with paramter",
"request":{
"uri":"/getwithparam",
"method":"get",
"queries":{
"name":"zhangsan",
"age":"18"
}
},
"response":{
"text":"This is response for Get request with paramter "
}
}
在瀏覽器中訪問:http://localhost:8888/getwithparam?name=zhangsan&age=18 就可以返回定義的json數據。
- Moco框架的http協議Post方法的Mock實現
1.不帶參數的post請求
[
{
"description":"This is Post request",
"request":{
"uri":"/postdemo",
"method":"post"
},
"response":{
"text":"This is Post response"
}
}
]
注意的是post請求不能直接在瀏覽器中訪問,這個時候我們就需要借助jmeter postman等測試工具進行post請求的測試了。具體方法這里不演示。
2.帶參數的post請求實現
{
"description":"This is Post request with paramter",
"request":{
"uri":"/postwithparam",
"method":"post",
"forms":{
"name":"zhangsan",
"age":"18"
}
},
"response":{
"text":"This is Post response with paramter"
}
}
- Moco框架如何加入Cookies
1.帶cookies信息的get請求
{
"description":"This is Get request with cookies",
"request":{
"uri":"/get/with/cookies",
"method":"get",
"cookies":{
"login":"true"
}
},
"response":{
"text":"This is get response with cookies"
}
}
2.帶cookies信息的post請求
{
"description":"This is Post request with cookies",
"request":{
"uri":"/post/with/cookies",
"method":"post",
"cookies":{
"login":"true"
}
"json":{
"name":"zhangsan",
"age":"18"
}
},
"response":{
"status":200,
"json":{
"zhangsan":"success",
"status":"1"
}
}
}
- Moco框架如何加入Header
Header請求頭信息的格式在get和post請求中是一致的。
{
"description":"This is Post request with header",
"request":{
"uri":"/postwithheader",
"method":"post",
"headers":{
"content-type":"application/json"
},
"json":{
"name":"zhangsan",
"age":"18"
}
},
"response":{
"text":"This is Post response with paramter"
}
}
- Moco框架如何進行重定向
1.重定向到baidu
{
"description":"redirect to www.baidu.com",
"request":{
"uri":"/redirect"
},
"redirectTo":"http://www.baidu.com"
}
2.重定向到自己網站的某個地址
{
"description":"redirect to my path",
"request":{
"uri":"/redirect2"
},
"redirectTo":"redirected"
},
{
"description":"This is my path",
"request":{
"uri":"/redirected"
},
"response":{
"text":"redirect success!"
}
}
如果喜歡作者的文章,請關注"寫代碼的猿"訂閱號以便第一時間獲得最新內容。本文版權歸作者所有,歡迎轉載.

