REST Assured
02 / 02

Reusable Specs, Auth & Error Paths

Reusable Specs, Auth & Error Paths

RequestSpecification & ResponseSpecification

// Centralize common setup — update ONE place, not every test method
RequestSpecification baseSpec = new RequestSpecBuilder()
    .setBaseUri("https://api.example.com")
    .addHeader("Accept", "application/json")
    .build();

ResponseSpecification successSpec = new ResponseSpecBuilder()
    .expectStatusCode(200)
    .expectContentType(ContentType.JSON)
    .build();

given().spec(baseSpec)
    .when().get("/users/1")
    .then().spec(successSpec).body("name", notNullValue());

Authentication

given().auth().basic("user", "pass")
    .when().get("/secure")
    .then().statusCode(200);

given().auth().oauth2(accessToken)
    .when().get("/secure")
    .then().statusCode(200);

Testing Error Paths

// Error responses deserve the same assertion rigor as success ones —
// clients depend on a stable error SHAPE to handle failures gracefully
@Test
void getUser_notFound_returnsStandardErrorShape() {
    given()
        .when().get("/users/99999")
        .then()
            .statusCode(404)
            .body("error.code", equalTo("USER_NOT_FOUND"))
            .body("error.message", notNullValue());
}

// Flexible matchers avoid brittleness against irrelevant variation
@Test
void listUsers_everyItemHasEmail() {
    given()
        .when().get("/users")
        .then()
            .body("users.email", everyItem(containsString("@")))
            .body("users.id", hasItems(1, 2, 3));
}

XML Responses

given()
    .when().get("/legacy/user/1")
    .then()
        .statusCode(200)
        .body(hasXPath("//user/name[text()='Alice']"));

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free