Search code examples
javajsonrest-assured

RestAssured Using Common Code


So I am a beginner to Rest Assured.

In JAVA, I have shortened code for illustration and ease. I have a class which has the following code:

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();
    }
}

Then another class which has:

public class BasicTest extends ApiEndpointHelper {
    @Test
    public void Query_endpoint() {
        String ActualResponse = ApiEndpointHelper.getId();

        assertJsonEquals(resource("responseExpected.json"),
                ActualResponse, when(IGNORING_ARRAY_ORDER));
    }
}

My Question is this:

How can I use code in such a way that common body items such as auth headers, content type, post URL etc can be declared somewhere and then all requests can get them? Also both uses same auth header but different passwords. Any clever way to make that work?! See in methods: 'postIdRequest' and 'getId'. I think I could use RequestSpecification but unsure how! Can someone explain with example, preferably using current context.


Solution

  • Extract common code into a method with parameters:

    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/");
        }
    }
    

    You can pass parameters for authentication if needed.

    Similarly you can extract URL construction into methods. It's all basic programming, so unless you have a specific problem, the question is probably too broad for Stackoverflow.