📜 ⬆️ ⬇️

REST-assured: useful tips

In this article, I gathered useful tips on using REST-assured, one of the most common Java libraries for automating REST-API testing.

All examples are vital, they are collected from my practice of conducting code-review in more than 50 projects with autotests.

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)...; //   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 in a hotel constant and pass it to the basePath, for example:

 //   url  http://host:port/appname/rest/someEndpoints private static final basePath = "/appname/rest/"; .. //       , //      : RestAssured.basePath = basePath; //     : 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:

 //   : given().header("content-type", "application/json").header("accept", "application/json")...; //   : 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, etc.


REST-assured provides a convenient syntax for testing every component of an HTTP response, but in practice you continue to encounter similar code:

 //   : Response response = given()...when().get(someEndpoint); Assert.assertEquals(200, response.then().extract().statusCode()); //   : given()...when().get(someEndpoint).then().statusCode(200); 

Use specifications


Code duplication is bad. Use specifications to reduce duplication. In REST-assured, you can create specifications for both the request and the response. In the specification of the request we make everything that can be duplicated in the queries.

 RequestSpecification requestSpec = new RequestSpecBuilder() .setBaseUri("http://localhost") .setPort(8080) .setAccept(ContentType.JSON) .setContentType(ContentType.ANY) ... .log(LogDetail.ALL) .build(); //       : RestAssured.requestSpecification = requestSpec; //   : given().spec(requestSpec)...when().get(someEndpoint); 

In the response specification we submit all checks that are duplicated from the request to the request.

 ResponseSpecification responseSpec = new ResponseSpecBuilder() .expectStatusCode(200) .expectBody(containsString("success")) .build(); //       : RestAssured.responseSpecification = responseSpec; //   : given()...when().get(someEndpoint).then().spec(responseSpec)...; 

You can create several specifications for different types of requests / responses and use them in the right situation.

Do not write your crutches to transform objects.


You should not convert your POJOs to JSON using a Jackson ObjectMapper, and then transfer the resulting string to the request body. REST-assured copes with this task. It uses the same Jackson or Gson, depending on what is in the classpath. JAXB is used to convert to XML. The original format is automatically determined by the Content-Type value.

 given().contentType(ContentType.JSON).body(somePojo) .when().post(EndPoints.add) .then() .statusCode(201); //        : SomePojo pojo = given(). .when().get(EndPoints.get) .then().extract().body().as(SomePojo.class); 

In addition, REST-assured does an excellent job of converting HashMap to JSON and back.

Use the power of groovy


The REST-assured library itself is written in Groovy and allows you to apply various methods from Groovy to the received JSON / XML response. For example:

 //  find, findAll         ,  collect       . //  it         Map<String, ?> map = get(EndPoints.anyendpoint).path("rootelement.find { it.title =~ 'anythingRegExp'}"); //     ,     Map<String, ?> map = get(EndPoints.anyendpoint).path("rootelement.findAll { element -> element.title.length() > 4 }"); //     sum, max, min     ,        String expensiveCar = get(EndPoints.cars).path("cars.find { it.title == 'Toyota Motor Corporation'}.models.max { it.averagePrice }.title"); 

Using methods from Groovy allows you to greatly reduce the amount of code you have written to search for the necessary value from the answer.

That's all, if you have more tips and examples, write them in the comments.

Source: https://habr.com/ru/post/421005/


All Articles