一、下載及安裝:
運行環境:
- JAVA環境
- linux
下載地址:https://github.com/dreamhead/moco
下載下來的是一個jar包,如:moco-runner-0.12.0-standalone.jar
把這個jar包上傳到linux服務器上,然后在與moco-runner-0.12.0-standalone.jar同級的目錄下創建 foo.json 文件:
[ { "response" : { "text" : "Hello, Moco" } } ]
Moco的運行非常簡單,只需要一行命令即可: java -jar <path-to-moco-runner> http -p <monitor-port> -c < configuration -file>
<path-to-moco-runner>
:moco-runner-0.11.0-standalone.jar包的路徑<monitor-port>
:http服務監聽的端口<configuration -file>
:配置文件路徑
java -jar moco-runner-0.12.0-standalone.jar http -p 9999 -c foo.json
通過瀏覽器訪問服務器的9999端口:
返回正確就說明Moco服務搭建成功了。
雖然說服務運行沒問題了,但是總覺得啟動和停止很麻煩,現在用shell來寫一個啟動和停止的腳本
啟動start.sh:
#!/bin/bash dirWiremock=`pwd` getCount=`ps -ef | grep "moco-runner" | grep -v "grep" |wc -l` wiremock_jar=${dirWiremock}/moco-runner-0.12.0-standalone.jar port=9999 exe_name=moco-runner if [ $getCount -ne 0 ]; then echo $exe_name is already running with $ssu_pid_count processes echo $exe_name started failed exit 1; else nohup java -jar ${wiremock_jar} http -p ${port} -c foo.json & echo "Start success!......" fi
停止stop.sh:
#!/bin/sh exe_name=moco-runner # 進入可執行目錄 base_path=$(cd `dirname $0`; pwd) cd $base_path # 停止進程 exe_pid_path=`pwd` exe_pid_list=`ps -ef | grep $exe_name|grep -v 'grep'|awk '{print $2}'` our_pid_list="" for exe_pid in $exe_pid_list do pid_path=`pwdx $exe_pid | awk '{print $2}'` if [ "$pid_path"x == "$exe_pid_path"x ]; then our_pid_list=$our_pid_list" "$exe_pid fi done if [ "$our_pid_list"x != "x" ]; then kill -9 $our_pid_list echo $exe_name process"$our_pid_list" killed else echo $exe_name is not running fi
運行shell腳本,啟動和停止就方便多了。
二、Moco配置
啟動服務之后,必然會根據需求stub出各種各樣接口反饋,我們會把這個配置放在一個json文件中,啟動Moco的時候,需要指定使用的配置文件路徑,這樣配置就可以生效了。Moco服務可以檢測到配置文件的變更,假如你修改了配置文件,不需要重新啟動Moco,服務照樣可以生效。更詳細的配置介紹請查看:https://github.com/dreamhead/moco/blob/master/moco-doc/apis.md
配置文件的工作原理大致如下:
如何在配置文件添加注釋
json不支持注釋,想要添加注釋的話,可以在description字段中加入描述
約定請求Body
約定接口的uri
約定請求參數
約定請求方法
約定HTTP版本
約定請求頭部
約定cookie
約定請求form
表單可以添加多項,多項的時候,必須全部匹配,接口才算匹配成功