How to perform REST API testing with Rest Assured


0 (7)

 

APIs are playing now an ever more important role in software trends (such as mobile applications), proper automated testing of these APIs is becoming indispensable. There are many different tools out there that can assist you in writing these automated tests at the API level.

What is API Testing ?

API testing is different than other testing as GUI is not available and are required to setup initial environment that invoke API with required set of parameters and then finally examine the test result.

Advantages:

  • Test of core functionality
  • Time effective
  • Test Quality
  • Faster Release

Types of Tools for API Testing:

  • Postman (Manual , Automation)
  • Rest Client (Manual)
  • SoapUI (Automation)
  • Poster (Manual)
  • Rest Assured (Automation)
  • Swagger (Manual , also uses for writing requirements)

We will going to show you how to use one of the most popular open-source tools for this: REST Assured

What is REST Assured ?

REST Assured is a Java library that provides a domain-specific language (DSL) for writing powerful, maintainable tests for RESTful APIs.

It supports the following types HTTP verbs (or methods):

  • POST
  • GET
  • PUT
  • DELETE
  • OPTIONS
  • PATH
  • HEAD

In the following sections, I’ll show you how to set up and configure REST Assured, write and run REST Assured tests, and apply some of its most powerful features. I’ll be using real-world code examples you can copy, run, and reuse directly in your own test automation efforts.

Getting started: Configuration

To get started with REST Assured, simply add it as a dependency to your project. If you’re using Maven, add the following entry to your pom.xml (change the version number to reflect the version you want to use):

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>3.0.2</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
</dependency>

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-junit</artifactId>
    <version>2.0.0.0</version>
</dependency>

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-core</artifactId>
    <version>1.3</version>
</dependency>

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-library</artifactId>
    <version>1.3</version>
</dependency>

<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.11</version>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

REST Assured can be used easily in combination with existing unit testing frameworks, such as JUnit and TestNG. For the examples presented in this tutorial, I used REST Assured with TestNG.

Once you have the import of REST Assured set up, add the following static imports to your test class:

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

Then you’re ready to create your first REST Assured test.

First test: Understanding the syntax

For this tutorial, we’ll test the countries.eu API, which can be found here. This API provides information about countries via a RESTful API.

Rest API Get Method

In the following example we are using the Rest-assured library’s “get” method to make an HTTP Get request to the restcountries.eu APIhttp://restcountries.eu/rest/v1/name/{countryName} that fetch the capital of a country. Then we will fetch the response in JSONArray and then use the TestNG’s assert method.

With REST Assured, you can not only verify response body contents, but also check the correctness of technical response data, such as the HTTP response status code, the response content type, and other response headers. The example below checks that:

The verification part of the test does the following:

  1. Captures the (JSON) response of the API call
  2. The response status code is equal to 200.
  3. The response content type (telling the receiver of the response how to interpret the response body) equals “application/json.”
package RestAPITest;

import static io.restassured.RestAssured.get;

import org.json.JSONArray;
import org.json.JSONException;
import org.testng.Assert;
import org.testng.annotations.Test;

import io.restassured.response.Response;

public class RestTest {

 @Test
 public void getRequestFindCapital() throws JSONException {
  given().
        when()
        .get("http://restcountries.eu/rest/v1/name/germany")
        .then()
        .assertThat()
        .contentType(ContentType.JSON)
        .and()
        .statusCode(HttpStatus.SC_OK)
        .log().all();
}

Note that the API used by REST Assured supports the familiar Given/When/Then syntax from Behavior-Driven development (BDD), resulting in a test that is easy to read and takes care of everything (setup, execution, and verification) with just a single line of code.

This example also shows how you can easily concatenate checks in a readable manner using the and() method, which is making the code more readable is all that it does.

Each one has a specific function:-

**Given**= a context or Getting a system in a particular state
**When**= something happens or Poke it
**Then**= we expect some outcome or examine the new state

Parameterizing tests

Often, you’ll want to repeat the same test with various sets of (input and output) parameters—a concept known as data-driven testing. Instead of writing a new test for each test data record, you’ll want to create a parameterized test and feed it with as many test data records as your desired test coverage requires.

RESTful APIs support two different types of parameters:

  • Query parameters: These are appended at the end of a RESTful API endpoint and can be identified by the question mark in front of them. For example, in the endpoint https://restcountries.eu/rest/v2/name/aruba?fullText=true, “fullText” is a query parameter (with value “true“).
@Test
public void getRequestWithQueryParamter()  {

    given()
            .queryParam("fullText","true")
            .when()
            .get("https://restcountries.eu/rest/v2/name/aruba")
            .then()
            .assertThat()
            .contentType(ContentType.JSON)
            .and()
            .statusCode(HttpStatus.SC_OK)
            .log().all();
}

Response Assertions

REST Assured also handles assertion within its library, the parsing of responses.

In the above example, we validated the output response message and generate response time. It provides various constructs for implementing assertions on cookies, response headers and response body. For doing assertions on response body it provides JsonPath for assertions on JSON responses and XmlPath for assertions on XML responses.

Accessing secured APIs

Often, APIs are secured using some sort of authentication mechanism. REST Assuredsupports basic, digest, form, and OAuth authentication. Here’s an example of how to call a RESTful API that has been secured using basic authentication (i.e., the consumer of this API needs to provide a valid username and password combination every time they call the API)

@Test
public void test_APIWithBasicAuthentication_ShouldBeGivenAccess() {
        
    given().
        auth().
        preemptive().
        basic("username", "password").
    when().
        get("http://path.to/basic/secured/api").
    then().
        assertThat().
        statusCode(HttpStatus.SC_OK);
}

Accessing an OAuth2-secured API is just as straightforward, assuming you have a valid authentication token:

@Test
public void test_APIWithOAuth2Authentication_ShouldBeGivenAccess() {
        
    given().
        auth().
        oauth2(YOUR_AUTHENTICATION_TOKEN_GOES_HERE).
    when().
        get("http://path.to/oath2/secured/api").
    then().
        assertThat().
        statusCode(HttpStatus.SC_OK);
}

Header & Status code

@Test
public void getResponseHeader() {

    String url = "http://restcountries.eu/rest/v1/name/germany";

    Response response = get(url);

    //Get All headers
    Headers allHeaders = response.getHeaders();
   // System.out.print(allHeaders);

    //Get as single header value
    String headerName = response.getHeader("Content-Type");
    //System.out.print(headerName);

    //Get Status Code
    int StatusCode = response.getStatusCode();
    System.out.print(StatusCode);
}

We can use REST Assured also in Performance Testing

@Test
public void getResponseTime() {

    // Get the response time in seconds from a get request
    String url = "http://restcountries.eu/rest/v1/name/germany";
    long timeInSeconds = get(url).timeIn(TimeUnit.SECONDS);

    given()
            .when()
            .get(url)
            .then().log().all()
            .time(lessThan(timeInSeconds));
}

Test Result:

java.lang.AssertionError: 1 expectation failed.
Expected response time was not a value less than <0L> milliseconds
, was 82 milliseconds (82 milliseconds).

Resources

If you want to learn more about REST Assured, take a look at the REST Assured usage guide on GitHub.

Good Luck & Happy Testing 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.