【问题标题】:RestAssured Using Common Code使用通用代码放心
【发布时间】:2018-02-13 17:54:47
【问题描述】:

所以我是放心的初学者。

在 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 但不确定如何使用! 有人可以举例说明,最好使用当前上下文。

【问题讨论】:

    标签: java json rest-assured


    【解决方案1】:

    将常用代码提取成带参数的方法:

    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 来说可能太宽泛了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-15
      • 2018-05-04
      • 2017-09-23
      相关资源
      最近更新 更多