rest-assured的默认值与Specification重用

一、默认值

  rest-assured发起请求时,默认使用的host为localhost,端口为8080,如果你想使用不同的端口,你可以这样做:

1 given().port(80)......

或者是简单点:

1 ..when().get("http://myhost.com:80/doSomething");

你也可能改变默认的baseURI、basePath、port和认证scheme:

 1 //域名或者IP
 2 RestAssured.baseURI = "http://myhost.com";
 3 //端口
 4 RestAssured.port = 80;
 5 //请求基本路径
 6 RestAssured.basePath = "/resource";
 7 //认证
 8 RestAssured.authentication = basic("username", "password");
 9 //根路径
10 RestAssured.rootPath = "x.y.z";

这就意味着,类似 get("/hello") 这样的一个请求,其实完整的请求为:http://myhost.com:80/resource/hello   ,并且使用基础授权认证"username" and "password"。关于根路径的设置后面再介绍。其他的默认值可以参考下面:

 1  // 默认过滤器list
 2 RestAssured.filters(..);
 3 //默认的request specification
 4 RestAssured.requestSpecification = ..    
 5  // 默认的response specification
 6 RestAssured.responseSpecification = ..
 7 //指定rest-assured对请求参数是否需要进行URL编码
 8 RestAssured.urlEncodingEnabled = .. 
 9 //如果没有注册解析器来处理响应体的content-type数据,指定默认值解析器
10 RestAssured.defaultParser = .. 
11 //为给定的content-type指定一个解析器
12 RestAssured.registerParser(..) 
13 //注销指定的content-type的解析器
14 RestAssured.unregisterParser(..) 

你也可以重置为标准的baseURL(localhost)、basePath(空)、标准端口port(8080)、标准根路径root path(" "),默认的认证scheme(none)以及URL编码(true),通过下面的方法重置:

1 RestAssured.reset();

 

二、Specification重用

  在不同的测试用例当中,我们可能会有重复的响应断言或者是请求参数,那么我们可以将重复的这一部分提取出来定义一个规范或者模板,这样的话在后续的测试用例当中就都可以使用这个规范模板了,为了达到这个效果,我们可以使用 RequestSpecBuilder ResponseSpecBuilder来实现。

1.ResponseSpecification重用

例如,你想在多个测试用例中,都使用这样的断言:判断响应状态码是否为200,并且Json数组"x.y"的大小是否等于2;  你可以定义一个ResponseSpecBuilder来实现这个功能:

 1 ResponseSpecBuilder builder = new ResponseSpecBuilder();
 2 builder.expectStatusCode(200);
 3 builder.expectBody("x.y.size()",is(2));
 4 ResponseSpecification responseSpec = builder.build();
 5 
 6 //接下来就可以在不同的测试用例中使用responseSpec
 7 when().
 8        get("/something").
 9 then().
10        spec(responseSpec).
11        body("x.y.z", equalTo("something"));

在这个例子中,需要重用的两个断言数据被定义在"responseSpec",并且与另外一个body断言合并,组成了这个测试用例中全部的断言,那么这个测试用例需要全部断言都通过用例结果才会通过,一旦其中一个断言失败,则测试用例的测试结果为失败。

 

2.RequestSpecification重用

  同样,假如你想在多个测试用例中重用请求数据,可以通过下面的代码来实现:

 1 RequestSpecBuilder builder = new RequestSpecBuilder();
 2 builder.addParam("parameter1", "parameterValue");
 3 builder.addHeader("header1", "headerValue");
 4 RequestSpecification requestSpec = builder.build();
 5   
 6 //接下来就可以在多个测试用例中使用requestSpec啦
 7 given().
 8         spec(requestSpec).
 9         param("parameter2", "paramValue").
10 when().
11         get("/something").
12 then().
13         body("x.y.z", equalTo("something"));    

这里的请求数据被合并在"requestSpec"中,所以这个请求包含了两个参数("parameter1"和"parameter2")以及一个头部("header1")。

posted @ 2018-01-12 19:52  lwjnicole  阅读(1807)  评论(0编辑  收藏  举报