[英]RestAssured Using Common Code
所以我是Rest Assured的初學者。
在 JAVA 中,為了便於說明和簡化,我縮短了代碼。 我有一個包含以下代碼的類:
public class ApiEndpointHelper {
public static String postIdRequest(String requestBody) {
String jsonBody = FileReader.getFile(requestBody);
Response response = RestAssured.given()
.auth()
.basic("userbob", "bobspassword")
.contentType(ContentType.JSON)
.body(jsonBody)
.when()
.post("http://localhost:8080/report/v1/");
response
.then()
.log().ifError().and()
.statusCode(200);
return response.asString();
}
public static String getId() {
Response response = RestAssured.given()
.auth()
.basic("NEWuserjames", "jamesspassword")
.contentType(ContentType.JSON)
.when()
.get("http://localhost:3099/v1/");
response
.then()
.log().ifError().and()
.statusCode(200);
return response.asString();
}
}
然后是另一個類:
public class BasicTest extends ApiEndpointHelper {
@Test
public void Query_endpoint() {
String ActualResponse = ApiEndpointHelper.getId();
assertJsonEquals(resource("responseExpected.json"),
ActualResponse, when(IGNORING_ARRAY_ORDER));
}
}
我的問題是這樣的:
我如何使用代碼,以便可以在某處聲明公共正文項(例如身份驗證標頭、內容類型、發布 URL 等),然后所有請求都可以獲取它們? 兩者都使用相同的身份驗證標頭但密碼不同。 有什么聰明的方法可以讓它發揮作用嗎?! 參見方法:'postIdRequest' 和 'getId'。 我想我可以使用 RequestSpecification 但不確定如何使用! 有人可以舉例說明,最好使用當前上下文。
將常用代碼提取為帶參數的方法:
public class ApiEndpointHelper {
private RequestSpecification givenAuthJson() {
return RestAssured.given()
.auth()
.basic("userbob", "bobspassword")
.contentType(ContentType.JSON)
}
public static String getId() {
Response response = givenAuthJson()
.when()
.get("http://localhost:3099/v1/");
}
}
如果需要,您可以傳遞參數以進行身份驗證。
同樣,您可以將 URL 構造提取到方法中。 這都是基本的編程,所以除非你有一個特定的問題,否則這個問題對於 Stackoverflow 來說可能太寬泛了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.