How to write API tests with REST Assured? - Part 2
Write readable API tests with the Java library REST Assured: Maven and JUnit setup, Given/When/Then, status, header and body checks, extracting values and debugging.
How to write API tests with REST Assured? - Part 2
API tests written with a plain HTTP client work, but they quickly turn into a lot of plumbing code: building the request, reading and parsing the body, and writing one assertion after another. Six months later, nobody can tell at a glance what a test checks. REST Assured is a Java library which solves this with a readable Given/When/Then style, and it has been the most popular choice for REST API tests on the JVM for years. In the previous article, we discussed what contract testing is and how it fits with the other types of tests. In this article, we are going to see what REST Assured is, how to set up a test project with Maven and JUnit, and how to write API tests with it.
Contract Testing series:
- What is contract testing and why do we need it?
- How to write API tests with REST Assured? (this article)
- How to write contract tests for a REST API with REST Assured?
- Contract testing use cases and best practices
TL;DR Summary
- REST Assured is a Java library for testing REST APIs with a fluent Given/When/Then syntax. It tests any HTTP API, whatever language the API is written in.
given()builds the request,when()sends it andthen()validates the response.- You can test the status code, the headers and the body (with Hamcrest matchers and JsonPath), extract values for the next request, and validate the response against a JSON schema.
- REST Assured works with JUnit and TestNG; we use JUnit 4 and Maven.
- Log the request and the response only when a validation fails, so the build output stays clean and the failures are easy to diagnose.
What is REST Assured?
REST Assured is an open source Java library to test and validate REST APIs. It brings the simplicity of dynamic languages like Groovy and Ruby to Java API testing, and it is available on Maven Central.
It follows the Given/When/Then structure of BDD (Behavior Driven Development),
- Given - the context: base URI, port, path, headers, query parameters and body of the request
- When - the action: the HTTP verb which sends the request
- Then - the outcome: the validations on the response
So, a test reads like a sentence: given this request, when I send a GET, then the status should be 200 and the body should contain the product.
An important point: REST Assured only talks HTTP. The API under test doesn’t have to be a Java API. In this series, the test project is a Java project, and the API is a Node.js API. This is exactly how a black-box contract test should work, because the contract is the HTTP interface, not the implementation behind it.
Why REST Assured?
| HTTP client + assertions | Postman scripts | REST Assured | |
|---|---|---|---|
| Language | Any | JavaScript | Java |
| Readability | Low (plumbing code) | Medium | High (Given/When/Then) |
| Lives with the code | Yes | Exported collections | Yes |
| Runs in the test runner and build pipeline | Yes | Through Newman | Yes (Maven or Gradle) |
| Best for | Very custom scenarios | Exploratory and QA automation | Developer-owned API and contract tests |
We still use Postman for exploring APIs and for QA automation (refer to the Postman Scripts series). For the tests which the development team owns and runs on every build, we prefer tests which live in source control next to the API and run in the same pipeline.
Setting up the test project
In this series, we use the ZYX Commerce product API as our example, the same API we used in the Postman Scripts series. It is a small Node.js API which runs at http://localhost:8081 and has two functions,
| Function | Uri |
|---|---|
| Get the available product list | GET /products |
| Get the product details for a given product | GET /products/{id} |
Follow the following instructions to set up the test project. You need JDK 8 and Maven installed.
-
Start the ZYX Commerce API. Navigate to the
ZYX Commerce\APIfolder of the attachment and run the following commands.npm install npm run serve -
Create a new Maven project for the tests.
mvn archetype:generate -DgroupId=com.zyx.commerce -DartifactId=zyx-commerce-api-tests -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false -
Add the REST Assured, JSON schema validator, Hamcrest and JUnit dependencies to the
pom.xml.<properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>3.1.0</version> <scope>test</scope> </dependency> <dependency> <groupId>io.rest-assured</groupId> <artifactId>json-schema-validator</artifactId> <version>3.1.0</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies>The
json-schema-validatormodule is used in the next article. REST Assured brings Hamcrest with it.
Your first API test
The following test checks that the product list API returns a 200 status code and a list of products.
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.greaterThan;
import org.junit.Test;
public class ProductListTests {
@Test
public void productList_shouldReturnProducts() {
given()
.baseUri("http://localhost")
.port(8081)
.header("Accept", "application/json")
.when()
.get("/products")
.then()
.statusCode(200)
.body("data.size()", greaterThan(0));
}
}
Let us walk through it,
given()starts building the request.baseUri,portand the path ingetdefine where the request goes.when().get("/products")sends the GET request.then()starts the validations on the response.statusCode(200)checks the status, andbodychecks a value in the JSON body with a JsonPath style expression and a Hamcrest matcher.data.size()is the number of items in thedataarray.- When an expectation fails, the JUnit test fails with a message like
Expected status code <200> doesn't match actual status code <500>.
Run the test from your IDE, or with Maven.
mvn test
Building the request
The given() section supports everything we need to build a request. A few commonly used options,
given()
.baseUri("http://localhost")
.port(8081)
.header("Accept", "application/json")
.header("Authorization", "Bearer <access token>")
.queryParam("search", "phone")
.queryParam("page", 1)
.when()
.get("/products")
.then()
.statusCode(200);
For a POST or PUT request, add the body in the given() section and use the matching verb in when().
given()
.baseUri("http://localhost")
.port(8081)
.contentType("application/json")
.body("{ \"name\": \"New product\", \"price\": 10.5 }")
.when()
.post("/products")
.then()
.statusCode(201);
Note: The ZYX Commerce API in this series is read-only, so the POST example above is only to show the syntax.
Testing the response
The then() section supports validations on the status code, the headers and the body. We can chain as many as we need, and REST Assured evaluates all the body expectations passed to one body call and reports every one which failed.
given()
.baseUri("http://localhost")
.port(8081)
.when()
.get("/products/29")
.then()
.statusCode(200)
.contentType(containsString("application/json"))
.body("success", equalTo(true),
"data.id", equalTo("29"),
"data.name", notNullValue());
The imports for the Hamcrest matchers are import static org.hamcrest.Matchers.*;. The common matchers are equalTo, notNullValue, containsString, greaterThan, hasSize, hasKey and everyItem.
Extracting values for the next request
Sometimes a test needs a value from one response for the next request, for example, the id of the first product in the list.
String firstProductId =
given()
.baseUri("http://localhost")
.port(8081)
.when()
.get("/products")
.then()
.statusCode(200)
.extract().path("data[0].id");
given()
.baseUri("http://localhost")
.port(8081)
.when()
.get("/products/" + firstProductId)
.then()
.statusCode(200);
Debugging a test
When a test fails and the reason isn’t obvious, add log() to see exactly what was sent and received. log().all() always writes the details, and log().ifValidationFails() writes them only when an expectation fails, which is what we want in the build.
given()
.log().ifValidationFails()
.baseUri("http://localhost")
.port(8081)
.when()
.get("/products")
.then()
.log().ifValidationFails()
.statusCode(200);
Organizing the tests
- Keep the host and port in one place, for example, in a base class, so the same tests can run against the local, Dev and QA environments.
- Create one test class per resource (e.g.
ProductListTests,ProductDetailsTests) and one test method per scenario. - Give the test methods meaningful names; the name is what you see in the build report when it fails.
- Keep these tests in a separate module or a separate Maven profile from the unit tests, because they need a running API.
import org.junit.BeforeClass;
import io.restassured.RestAssured;
public abstract class ApiTestBase {
@BeforeClass
public static void configure() {
RestAssured.baseURI = System.getProperty("api.host", "http://localhost");
RestAssured.port = Integer.parseInt(System.getProperty("api.port", "8081"));
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
}
}
Now each test only needs given().when().get("/products").then()..., and we can point the tests to another environment with mvn test -Dapi.host=https://dev.example.com -Dapi.port=443.
Wrap up
In this article, we have looked at what REST Assured is and why we use it, how to set up a Maven and JUnit test project, and how to write API tests with it: building the request, testing the status, headers and body, extracting values, debugging and organizing the tests. I really appreciate that you took the time to read this article. In the next article, I will walk you through how to write contract tests for the ZYX Commerce API with REST Assured, including the JSON schema validation and the error contract.
Related Posts
How to write contract tests for a REST API with REST Assured? - Part 3
Define the contract of a REST API, express it as JSON schemas and write contract tests with REST Assured that catch breaking changes but allow additive ones.
Contract testing use cases and best practices - Part 4
Real-world use cases of contract testing, when to move to consumer-driven contracts with Pact, and the best practices and pitfalls we follow.
What is contract testing and why do we need it? - Part 1
What an API contract is, why we need contract testing, how it fits with unit, integration and end-to-end tests, and provider-driven versus consumer-driven approaches.