使用Moco搭建Mock Server教程

Moco是一个简易的Mock Server搭建工具

Github开源链接:https://github.com/dreamhead/moco

 一、准备工作

1. 下载Standalone Moco Runner

2.电脑需要安装Java环境

二、运行Moco

打开terminal,运行命令

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

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

<monitor-port>:http服务监听的端口

<configuration -file>:配置文件路径

 示例:

三、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"
    }
}

关于HTTP的API想要学习更多,可以前往官方文档:https://github.com/dreamhead/moco/blob/master/moco-doc/apis.md

猜你喜欢

转载自www.cnblogs.com/luffa/p/10389151.html