使用moco搭建mockserver

下载 moco-runner-standalone
http://central.maven.org/maven2/com/github/dreamhead/moco-runner/0.12.0/moco-runner-0.12.0-standalone.jar

如果我们想实现如下的情况,

1. 请求http://localhost:port/we/bobemockedapi 时 我们自定义mock 返回数据

2. 如果请求http://localhost:port/we/* (* 除了 /we/bobemockedapi ) 其他的均自动反向代理到 另外一个服务器 http://realserver/

3. 如果没有匹配到任何规则, 则走默认的mock数据返回。 返回 {“mockserver”:”this is the default response by mock server”}

那么我们先编写一个test.json 配置文件, 具体的文件配置如下。 我们需要将反向代理的配置放到所有的mock 的uri 配置之后。 这样所有没有匹配到的uri, 都会总默认的反向代理。

[
{
"request" :
{
"uri" : "/we/bobemockedapi"
},
"response" :
{
"json":
{"responsedata":"mock response data"}
}
}
,

{
"proxy" : {
"from" : "/we",
"to" : "http://realserver"
}
},

{
"request" :
{
"uri" : {
"match": "/.*"
}
},
"response" :
{
"json":{"mockserver":"this is the default response by mock server"}
}
}
]

然后启动mock server, port 是你要指定的端口号
java -jar moco-runner-0.12.0-standalone.jar http -p port -c test.json

启动后我们可以curl进行测试验证了。

$curl http://localhost:port/we/bobemockedapi
${"responsedata":"mock response data"}

$ curl http://localhost:port/we/notmockedapi
$ 这里返回的内容是 http://realserver/notmockedapi 返回的内容

$ curl http://localhost:port/hissummer/notmockedapi (没有匹配到其他的, match到了 "/.*" , 所以返回了默认的mock内容)
$ {"mockserver":"this is the default response by mock server"}

此篇文章已被阅读1116 次

Tags:

Add a Comment

邮箱地址不会被公开。 必填项已用*标注