代码之家  ›  专栏  ›  技术社区  ›  worrynerd

重启:如何为端点调用类型创建抽象层

  •  1
  • worrynerd  · 技术社区  · 8 年前

    这是我对GET端点的重启调用:

    public static Response getCall(int expectedStatusCode){
        return given()
                .port(PORT)
                .contentType(ContentType.JSON)
                .when()
                .log().all()
                .get(getEndpoint)
                .then()
                .log().all()
                .assertThat()
                .statusCode(expectedStatusCode).extract().response();
    }
    

    以下是对POST端点的调用:

    public static Response postEndpoint(Request request, int expectedStatusCode) {
        return given()
                .port(PORT)
                .contentType(ContentType.JSON)
                .body(request)
                .when()
                .log().all()
                .post(postEndpointURI)
                .then()
                .log().all()
                .assertThat()
                .statusCode(expectedStatusCode).extract().response();
    }
    

    由于其可见的代码是冗余的,唯一的区别是调用、POST和GET的类型。

    我如何使代码抽象化,并使调用不同?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Andrei Sfat systemfreund    8 年前

    希望它能对你的冗余问题有所帮助。您可能会从这里获得更多改进重构的想法。

    private static final int PORT = 1922;
    private static String getEndpoint;
    private static String postEndpointURI;
    
    /**
     * First part of the building up the request
     */
    private static RequestSpecification buildRequest() {
        return given()
                .port(PORT)
                .contentType(ContentType.JSON)
                .when()
                .log().all();
    }
    
    /**
     * Relevant part of the GET request
     */
    private static Response buildGetRequest() {
        return buildRequest().get(getEndpoint);
    }
    
    /**
     * Relevant part of the POST request
     */
    private static Response buildPostRequest(Request request) {
        return buildRequest().body(request).post(postEndpointURI);
    }
    
    /**
     * Last bit redundant that was called by both calls
     */
    private static Response extractResponse(Response response, int expectedStatusCode) {
        return response.then()
                .log().all()
                .assertThat()
                .statusCode(expectedStatusCode).extract().response();
    }
    
    
    /**
     * Your main GET method
     */
    public static Response assertThatGetResponseStatusIs(int expectedStatusCode) {
        return extractResponse(buildGetRequest(), expectedStatusCode);
    }
    
    /**
     * Your main POST method
     */
    public static Response assertThatPostResponseStatusIs(Request request, int expectedStatusCode) {
        return extractResponse(buildPostRequest(request), expectedStatusCode);
    }
    
    public static void main(String[] args) {
        System.out.println(assertThatGetResponseStatusIs(500));
        System.out.println(assertThatPostResponseStatusIs(request, 400));
    }