使用Moco搭建Mock Server教程

Moco是一個簡易的Mock Server搭建工具javascript

Github開源連接:https://github.com/dreamhead/mocojava

 

 1、準備工做git

1. 下載Standalone Moco Runnergithub

2.電腦須要安裝Java環境json

 

2、運行Mocoapi

打開terminal,運行命令跨域


java -jar <path-to-moco-runner> http -p <monitor-port> -c < configuration -file>

<path-to-moco-runner>:moco-runner-xxx-standalone.jar包的路徑bash

<monitor-port>:http服務監聽的端口app

<configuration -file>:配置文件路徑maven

 示例:

 

 

 

3、mock.json文件編寫示例(針對http請求)

PS:通常使用Mock Server都是臨時替代正規server的做用,特別是正式的server沒有開發好的時候,因此重點是API與數據格式是否正確,通常不會做數據保存、複雜的參數校驗以及上傳數據格式校驗這些。

1. GET請求

// 普通的GET請求
{
    "request" :
    {
        "method" : "get",
        "uri" : "/api/image_management/"
    },
    "response" :
    {
        "json" : {...}
    }
} 
// GET請求中帶ID
{
    "request" :
    {
        "method" : "get",
        "uri": {"match": "/api/image_management/[0-9]*/"}
    },
    "response" :
    {
        "json" : {...}
    }
}    
// GET請求中帶Query
{
	"request" :
	{
	    "method" : "get",
	    "uri": { "match": "/api/image_management/list_usage/"},
	    "queries":
        {
            "usage": "xxx"
        }
	},
	"response" :
	{
	    "json" : {...}
	}
}

  

2. POST 請求

// 不做上傳數據校驗,簡易的POST
// Query與url中帶ID能夠參考上面的GET請求,這裏再也不贅述
{
    "request" :
    {
        "method" : "post",
        "uri" : "/api/keys/",
        "headers" : 
        {
            "content-type" : "application/json"
        }
    },
    "response" :
    {
        "json" : {...}
    }
}    

 

3. PUT

// 操做大體同上面POST
{
        "request" :
        {
	    "method" : "put",
	    "uri" : {"match": "/api/job_management/configuration/[0-9]*/"},
	    "headers" : 
            {
                "content-type" : "application/json"
            }
        },
        "response" :
        {
            "json" : {...}
        }
}

 

4.DELETE

// 後面的.*能夠與任意字符串做匹配
{
    "request" :
    {
       "method" : "delete",
       "uri" : {"match": "/api/job_management/instance/.*"}
    },
    "response" :
    {
       "text" : "success"
    }
}

 

跨域問題的解決:

須要給reponse設置access control

[
  {
	  "request" :
	  {
	  	"method" : "get",
	  	"uri" : "/api/image_management/"
	  },
	  "response" :
	  {
	  	"headers" :
                {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods":"PUT,POST,GET,DELETE,OPTIONS",
                "Access-Control-Allow-Headers": "Content-Type,Content-Length, Authorization, Accept,X-Requested-With"
             },
	  	"json" : ["test1", "test2", "test3"]
	  }
	}
]

  

關於HTTP的API想要學習更多,能夠前往官方文檔:https://github.com/dreamhead/moco/blob/master/moco-doc/apis.md

相關文章
相關標籤/搜索