一个简单搭建模拟服务器的程序库。
https://github.com/dreamhead/mocohttps://repo1.maven.org/maven2/com/github/dreamhead/moco-runner/0.11.0/moco-runner-0.11.0-standalone.jarjava -jar moco-runner-<version>-standalone.jar start -p 12306 -c foo.json[ { "response" : { "text" : "Hello, Moco" } } ]然后就可以通过http://localhost:12306访问了
[{"request" :{"text" : "foo"},"response" :{"text" : "bar"}}]访问:http://localhost:12306
如果request内容太多,可以放到一个文件里面
{
"request" :
{
"file" : "foo.request"
},
"response" :
{
"text" : "bar"
}
}PS:Moco支持动态加载配置文件,所以无论你是修改还是添加配置文件都是不需要重启服务的
Moco支持在全局的配置文件中引入其他配置文件,这样就可以分服务定义配置文件
例如你有两个项目Boy和Girl项目需要使用同一个Mock Server,那么可以分别定义boy.json和girl.json配置文件,然后在全局文件中引入即可: 全局配置如下:
[ { "context": "/boy", "include": "boy.json" }, { "context": "/girl", "include": "girl.json" } ]在boy.json和girl.json中分别定义:
//boy
[ { "request" : { "uri" : "/hello" }, "response" : { "text" : "I am a boy." } } ]
//girl
[ { "request" : { "uri" : "/hello" }, "response" : { "text" : "I am a girl." } } ]此时需要通过参数-g在加载全局配置文件(-g仅仅在3.1context章节使用)
java -jar moco-runner-<version>-standalone.jar start -p 12306 -g onecoder.json启动成功后,我们分别通过http://localhost:12306/girl/hello 和 http://localhost:12306/boy/hello 访问服务,便可得到对应的reponse结果。 其实全局文件的引入方式还有直接include等,不过OneCoder觉得context这种方式应该比较常用,
Request参数
request里自然有很多带参数的,配置如下:
[{ "request" : { "uri" : "/getBoy", "queries": { "name":"onecoder" } }, "response" : { "text" : "Hey." } }]上述配置匹配的url即为:http://localhost:12306/getBoy?name=onecoder,返回值即为: Hey. 也就是说,使用这种方式你需要在开发期有固定的测试参数和参数值
对于rest风格的url,Moco支持正则匹配。
[{ "request": { "uri": { "match": "/searchboy/\\w+" } }, "response": { "text": "Find a boy." } }]此时,访问http://localhost:12306/searchboy/* 结尾加任何参数均可匹配到。
除了Get外,Post,Put,Delete等请求模式自然是支持的:
[{
"request" :
{
"method" : "post",
"forms" :
{
"name" : "onecoder"
}
},
"response" :
{
"text" : "Hi."
}}]对于Header、Cookies等请求信息的配置也是支持的。
[{"request": {"uri": "/template"},"response": {"text": {"template": "${req.queries['name']}"}}}]此时通过url:http://localhost:12306/template?name=onecoder 访问,则会返回onecoder。 这样就可以通过template这种方式灵活的返回一些值。
[{ "request" : { "uri" : "/redirect" }, "redirectTo" : "http://www.coderli.com" }]["request":{"uri":"/event"},"response":{"text":"event"},"on":{"complete":{"async":"true","post":{"url":"http://another_siter","content":"cintent"}}}] 这样,对于/event的访问将会是异步的。要等到对http://another_siter访问结束后,才会将结果放到response里
https://github.com/dreamhead/moco/blob/master/moco-doc/socket-apis.md https://github.com/dreamhead/moco/blob/master/moco-doc/rest-apis.md https://github.com/dreamhead/moco/blob/master/moco-doc/apis.md
PS: 原文MardDown格式下载
链接: https://pan.baidu.com/s/1zsx19iHQGYNarGo09G6PHw 密码: hnse