使用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

相关文章
相关标签/搜索