Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用公共代码重新启动_Java_Json_Rest Assured - Fatal编程技术网

Java 使用公共代码重新启动

Java 使用公共代码重新启动,java,json,rest-assured,Java,Json,Rest Assured,所以我是一个初学者,请放心 在JAVA中,为了便于演示和使用,我缩短了代码。我有一个具有以下代码的类: public class ApiEndpointHelper { public static String postIdRequest(String requestBody) { String jsonBody = FileReader.getFile(requestBody); Response response = RestAssured.gi

所以我是一个初学者,请放心

在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));
    }
}
我的问题是:

我如何使用代码,使常见的主体项(如auth头、内容类型、post URL等)可以在某处声明,然后所有请求都可以获取它们?此外,两者都使用相同的身份验证头,但密码不同。有什么聪明的方法能让它工作吗?! 请参见方法中的:“PostdRequest”和“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来说可能太广泛了