一、默認值
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")。