In this article, I gathered useful tips on using REST-assured, one of the most common Java libraries to automate REST-API testing.
All examples are vital, they are collected from my practice of conducting code-review in more than 10 projects with automation tests.
Take end-points to a separate place.
It would seem that this is obvious. But no, quite often you have to see code with hard endpoints in the request.
It is best to endpoints in static constants of the final class. At the same time, the anti-pattern “constant interface” should be avoided – this is a bad practice.
Do not forget that REST-assured allows you to take out the parameters of the path, for example:
public final class EndPoints { public static final String users = "/users/{id}"; ... } given().pathParams("id", someId).get(EndPoints.users)...; //or given().get(EndPoints.users, someId)....
Also, if in many queries you use the same base path, then it will be good practice to put it into a hotel constant and pass it to the basePath, for example:
// we can set the base path at the global level // it will apply to all requests: RestAssured.basePath = basePath; //or at the level for a single request: given().basePath(basePath)...
The same applies to the host and port of the application under test.
ContentType/Accept
These headers are used in almost all HTTP requests. Understanding this, the REST-assured authors made it possible to install them by calling special methods:
// bad practice: given().header("content-type", "application/json").header("accept", "application/json")...; // good practice: given().contentType(ContentType.JSON).accept(ContentType.JSON)...;
A good practice would be to set these headers in a specification or globally. This will increase the readability of your code.
StatusCode
REST-assured provides a convenient syntax for checking every component of an HTTP response, but in practice you continue to encounter similar code:
// bad practice: Response response = given()...when().get(someEndpoint); Assert.assertEquals(200, response.then().extract().statusCode()); // good practice: given()...when().get(someEndpoint).then().statusCode(200);
That’s all, if you have more tips and examples, write them in the comments.