我很高兴地宣布,Moco 0.11.0发布了。 Moco是什么? Moco是一个可以轻松搭建测试服务器的框架/工具/程序库。 变更 本次发布主要增加了两个大的特性:REST API 和 JUnit 集成。 众所周知,REST 服务几乎已经成了现代服务端开发的标配。为了简化 REST API 的模拟,Moco 专门提供了特定的 API,比如,下面这个例子: 1 2 3 4 5 6 7 8 | RestServer server = restServer(port, log());
ResourceObject resource = new ResourceObject();
resource.code = 1 ;
resource.message = "hello" ;
server.resource( "targets" ,
get( "1" ).response(toJson(resource))
);
|
RestServer 的 resource 方法是为配置资源而设计的,主要配置资源的名字,以及访问的设置。这里的例子里,我们声明了一个名为 targets 的资源,我们还配置了一个 get 方法,当资源 ID 为1时,返回相应的对象。这个配置可以通过 /targets/1 访问得到。 REST API 同样支持 JSON 配置文件,上面的例子用 JSON 配置文件的形式可以写成如下格式: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | [
"resource": {
"name": "targets",
"get": [
{
"id": "1",
"response": {
"json": {
"code": 1,
"message": "foo"
}
}
}
]
}
]
|
访问 REST API 的文档可以了解更多细节。 Moco 的 JUnit 集成是利用 JUnit 的特性,进一步简化测试代码的编写。 1 2 3 4 5 6 7 8 9 | public class MocoJunitJsonHttpRunnerTest {
@Rule
public MocoJunitRunner runner = MocoJunitRunner.jsonHttpRunner( 12306 , "foo.json" );
@Test
public void should_return_expected_message() throws IOException {
Content content = Request.Get( "http://localhost:12306" ).execute().returnContent();
assertThat(content.asString(), is( "foo" ));
}
}
|
这里声明了一个 JUnit 的规则(Rule),它会在测试运行之前启动一个 Moco 服务器,在测试运行完毕之后关闭它。利用 Rule 的特性,就不必在每个测试里去启停 Moco 服务器了。 更多发布相关信息,请参考 Release Notes。 |