Overview
REST Assured is a Java library that implements a DSL for easily validating REST API based services by abstracting low-level details of HTTP requests and of parsing responses.
It provides a syntax based on Gherkin (i.e. given, when, then) for better readibility.
From REST Assured documentation, imagine that you have a REST based service accessibile in the http://localhost:8080/lotto/{id} endpoint, and returning a JSON content.
{ "lotto":{ "lottoId":5, "winning-numbers":[2,45,34,23,7,5,3], "winners":[ { "winnerId":23, "numbers":[2,45,34,23,3,5] }, { "winnerId":54, "numbers":[52,3,12,11,18,22] } ] } }
A JUnit test to check that the HTTP response code is OK (i.e. 200) and that the "lotto" object returned is correct, could be something as follows.
@Test public void lotto_resource_returns_200_with_expected_id_and_winners() { when(). get("/lotto/{id}", 5). then(). statusCode(200). body("lotto.lottoId", equalTo(5), "lotto.winners.winnerId", hasItems(23, 54)); }
This takes advantage of the JsonPath, a simple JSON parser. There's also an equivalent for XML (i.e. XmlPath).
Description
In this tutorial, we'll use the code from Bas Dijkstra open-source workshop on REST Assured.
We aim to test a service that provides an API (i.e. http://api.zippopotam.us/) to obtain location data based on postal/zip codes on several countries.
The workshop provides some exercises, stored under src/test/java/exercises; it also provides the answers.
As an example, lets perform verify that the response contains an API request for obtaining the information
/*********************************************** * Send a GET request to /us/90210 and check * that the state associated with the first place * in the list returned is equal to 'California' * * Use the GPath expression "places[0].state" to * extract the required response body element **********************************************/ @Test public void requestUsZipCode90210_checkStateForFirstPlace_expectCalifornia() { given(). spec(requestSpec). when(). get("/us/90210"). then(). assertThat(). body("places[0].state", equalTo("California")); }
mvn clean compile test -Dtest=answers.* junit-merge -d target/surefire-reports/ -o merged-test-results.xml