REST Assured 系列汇总 之 REST Assured 7 - 链式调用方法
困惑:
你如果参考一些有关Rest Assured教程,会看到如下的例子:
@Test public void
lotto_resource_returns_200_with_expected_id_and_winners() {
when().
get("/lotto/{id}", 5).
then().
statusCode(200).
body("lotto.lottoId", equalTo(5),
"lotto.winners.winnerId", hasItems(23, 54));
}
初学者对上面的语法会有一些困惑。本文目的就是解决这个困惑,所以我们暂且忘记这个例子,让我们先从基本的了解开始。
链式调用:
下面这个这个类有三个非static方法:
public class NonBuilderPattern {
public void M1()
{
System.out.println("M1");
}
public void M2(String str)
{
System.out.println("Pass string is "+str);
}
public void M3()
{
System.out.println("M3");
}
public static void main(String[] args) {
NonBuilderPattern nbp = new NonBuilderPattern();
nbp.M1();
nbp.M2("Kelly");
nbp.M3();
}
}
输出:
M1
Pass string is Kelly
M3
上面的方法返回类型都是void,我们用实例名来分别调用这些方法。现在让我们改变方法的返回类型为类名,返回值为this,它总是指向当前的对象。
public class BuilderPattern {
// Change return type of each method as Class type
// "this" always points to current/calling object. Returning the same to
// have same reference
public BuilderPattern M1()
{
System.out.println("M1");
return this;
}
public BuilderPattern M2(String str)
{
System.out.println("Pass string is "+str);
return this;
}
public BuilderPattern M3()
{
System.out.println("M3");
return this;
}
public static void main(String[] args) {
BuilderPattern nbp = new BuilderPattern();
nbp.M1().M2("Kelly").M3();
}
}
输出:
M1
Pass string is Kelly
M3
**nbp.M1().M2(“Amod”).M3();**也被称为链式,以链式的方式调用方法。
REST Assured 运用链式调用:
REST Assured也大量的使用相同思想,有助于你创建链式的脚本。例如:RequestSpecification 接口,这个接口用来向request body里设置headers,params,authentication,body,cookies,proxy等等。这个接口的大部分方法的返回类型就是RequestSpecification 接口本身,所有你可以创建如下的链式方法。
RequestSpecification req= RestAssured.given()
.accept(ContentType.JSON)
.auth().preemptive().basic("username", "password")
.header("headername", "headervalue")
.param("paramname", "paramvalue")
.cookie("cookieName", "value");
上面的代码也等同如下代码:
RequestSpecification req= RestAssured.given();
req= req.accept(ContentType.JSON);
req= req.auth().preemptive().basic("username", "password");
req= req.header("headername", "headervalue");
req= req.param("paramname", "paramvalue");
req= req.cookie("cookieName", "value");
现在,你对最初的例子不再困惑了吧。结合前面Staic import的介绍,REST Assured大量运用这两个理念,当然这些不是强制的,可以根据自己的习惯运用。