詳解構建mock服務最方便的神器 Moco

moco 介紹

moco 框架是 github 上的一個開源項目,可模擬 http,https,Socket 協議的 mock 操作。如果大家不瞭解什麼是 mock 請參考文章:

什麼是 mock

這裏重點介紹 moco 的 standolone 方式的用法!下載地址:
https://github.com/dreamhead/moco,點擊下圖中的 Download Standalone Moco Runner 即可

啓動 moco 非常的簡單

java -jar moco-runner--standalone.jar http -p 9999 -c test.json

這個命令也非常容易理解(把 test.json 放到 moco.jar 的相同目錄即可)

http 表示使用的協議。Moco 支持 http,https,Socket 三種協議

-p 表示使用的端口 ,不使用該參數默認啓動端口 58593

-c 是定義的 mock 請求和與其對應的響應文件,使用 json 格式,示例如下:

[{"request":{"uri":"/hello"},"response":{"text":"moco"}}]

此時我們在瀏覽器輸入:
http://127.0.0.1:9999/hello 回看到瀏覽器中顯示信息 moco。這就是最簡單的 moco mock 的實例!大家是不是感覺到使用 moco 創建 mock 簡直方便到起飛!

moco 命令介紹

常用命令如下:

http 實例,前面已經介紹

java -jar moco-runner--standalone.jar http -p 12306 -c foo.json

https 實例

java -jar moco-runner--standalone.jar https -p 12306 -c foo.json --https /path/to/cert.jks --cert mocohttps --keystore mocohttps

同時處理多個 json 請求

java -jar moco-runner--standalone.jar http -p 12306 -c "*.json"

備註: 該命令在 windows 系統中運行報錯,建議在 linux 系統中運行,親測 centos 運行正常。

java -jar moco-runner--standalone.jar http -p 12306 -g settings.json

我們可以統一設置要執行的 json 文件(即配置文件),當 json 文件非常多時,這種方式顯然能夠提升執行效率,具體代碼如下:

[{"include" : "foo.json"},{"include" : "bar.json"}]

更多信息可以參考

https://github.com/dreamhead/moco/blob/master/moco-doc/global-settings.md

其他參數

-q 使用 Quiet 模式,該模式下不會顯示請求和響應的詳細信息

Version 查看 moco 的版本信息

-s 9527 關閉 moco

Json 文件常用實例

在一個 json 文件中設置多個請求,一個 get 請求,一個 post 請求並且是 json 格式,一個是使用了 template 函數的 get 請求

[{"request":{"uri":"/withGetDemo","method":"get"},"response":{"text":"this is a get method "}},{"request":{"uri":"/withPostDemo","method": "post","headers": {"content-type": "application/json"},"json": {"name": "xiaoming","age": "18"}},"response":{"text":"this is a post method"}},{"request": {"uri": "/template"},"response": {"text": {"template": "${now(\"yyyy-MM-dd\")}"}}}]

其他 api 詳情請參考

https://github.com/dreamhead/moco/blob/master/moco-doc/apis.md

更多實例請參考

https://github.com/dreamhead/moco/tree/master/moco-runner/src/test/resources

moco 的不足

使用 moco 有二週的時間了,暫時總結了兩點不足:

  1. 新添加的 json 文件,不能立即生效,需要重啓 moco-runner--standalone.jar,如果多人同時使用 moco,新增或者更新 mock 時,需要協調通知。

  2. Mock 的請求不能存儲到數據庫中,對於統計 mock 歷史請求結果不夠友好,如果想進一步解決該問題,需要編寫代碼解析日誌來完成對 mock 請求信息的統計

來源:

https://www.toutiao.com/article/7129709173151007264/?log_from=93cb9d8513ab3_1660527620374

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/PRmpHVZD-xzapGOjjNyX_g