Mock就是模擬接口的。本文學習Mock的 Moco開源框架。java
Moco源碼和jar下載地址: git jar 下載moco-runner-xxxx-standalone.jargit
Step1: 在項目中建立一個package:moco,並將下載的jar包放在該package下。github
Step2:建立一個json文件,格式以下: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瀏覽器
在命令行中出現,則命令運行成功cookie
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文件中定義的數據。app
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實現:maven
{ "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數據。ide
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" } }
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" } } }
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" } }
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!" } }
若是喜歡做者的文章,請關注"寫代碼的猿"訂閱號以便第一時間得到最新內容。本文版權歸做者全部,歡迎轉載.