DevQAExpert

Beginning with Rest Assured:

You must first set up your environment for testing and project dependencies before you can start using Rest Assured. Using build automation technologies like Gradle or Maven, you can quickly integrate Rest Assured into your current Java project. Once everything is set up, you can begin creating API tests using the expressive syntax of Rest Assured, sending HTTP requests, and verifying replies. For handling headers, cookies, and other request/response parameters, Rest Assured also offers simple techniques.

Setup and Execution:

Follow the simple 4  Step Process To Setup Run and Execute the Rest Assured Tests : 

Let’s take a simple example of evaluating the functioning of a user registration endpoint to show how to set up and run API tests using Rest Assured.

1. Set up the Project:

Create a new Java project to get started, then add the required dependencies to your build automation tool (such as Gradle or Maven). Add the Rest Assured library and any other necessary requirements to your project’s dependency list.

2. Creating the Test Case

Import the required Rest Assured classes into a new test class. Create a test method to represent the functionality to get started.

3. Establish the test logic:

Include the request information, including the base URI, endpoint, request body, and any relevant headers, in the method. then execute the GET, POST, PUT, PATCH, DELETE etc. request, and check the outcome

4. Test execution:

Use your favorite testing framework or IDE to run the test case. Sending the HTTP request to the specified endpoint, receiving the response, and making the requested assertions are all handled by Rest Assured. The outcomes of the test will show whether or not the API registration feature is performing as planned.

 

Writing Your First API Test with Rest Assured

Add the following dependencies according to your tool setup : 

Maven / Gradle Users

Add the following dependency to your pom.xml:

REST Assured

Includes JsonPath and XmlPath

——————————————————————-

Maven:

<dependency>

      <groupId>io.rest-assured</groupId>

      <artifactId>rest-assured</artifactId>

      <version>5.3.0</version>

      <scope>test</scope>

</dependency>

Gradle:

testImplementation ‘io.rest-assured:rest-assured:5.3.0’

———————————————————————–

Notes

  1. You should place rest-assured before the JUnit dependency declaration in your pom.xml / build.gradle in order to make sure that the correct version of Hamcrest is used.
  2. REST Assured includes JsonPath and XmlPath as transitive dependencies


JsonPath

Standalone JsonPath (included if you depend on the rest-assured artifact). Makes it easy to parse JSON documents. Note that this JsonPath implementation uses Groovy’s GPath syntax and is not to be confused with Kalle Stenflo’s JsonPath implementation.

——————————————————————-

Maven:

<dependency>

      <groupId>io.rest-assured</groupId>

      <artifactId>json-path</artifactId>

      <version>5.3.0</version>

      <scope>test</scope>

</dependency>

Gradle:

testImplementation ‘io.rest-assured:json-path:5.3.0’

——————————————————————-


XmlPath

Stand-alone XmlPath (included if you depend on the rest-assured artifact). Makes it easy to parse XML documents.

——————————————————————-

Maven:

<dependency>

      <groupId>io.rest-assured</groupId>

      <artifactId>xml-path</artifactId>

      <version>5.3.0</version>

      <scope>test</scope>

</dependency>

Gradle:

testImplementation ‘io.rest-assured:xml-path:5.3.0’

——————————————————————-


JSON Schema Validation

If you want to validate that a JSON response conforms to a Json Schema you can use the json-schema-validator module:

——————————————————————-

Maven:

<dependency>

      <groupId>io.rest-assured</groupId>

      <artifactId>json-schema-validator</artifactId>

      <version>5.3.0</version>

      <scope>test</scope>

</dependency>

Gradle:

testImplementation ‘io.rest-assured:json-schema-validator:5.3.0’

——————————————————————-

Refer to the documentation for more info.

Spring Mock Mvc

If you’re using Spring Mvc you can now unit test your controllers using the RestAssuredMockMvc API in the spring-mock-mvc module. For this to work you need to depend on the spring-mock-mvc module:

——————————————————————-

Maven:

<dependency>

      <groupId>io.rest-assured</groupId>

      <artifactId>spring-mock-mvc</artifactId>

      <version>5.3.0</version>

      <scope>test</scope>

</dependency>

Gradle:

testImplementation ‘io.rest-assured:spring-mock-mvc:5.3.0’

——————————————————————-

Using Kotlin? Refer to the documentation for Kotlin extension functions that makes it nicer to work with the Spring Mock Mvc module.


Spring Web Test Client

If you’re using Spring Webflux you can now unit test your reactive controllers using the RestAssuredWebTestClient API in the spring-mock-mvc module. For this to work you need to depend on the spring-web-test-client module:

——————————————————————-

Maven:

<dependency>

      <groupId>io.rest-assured</groupId>

      <artifactId>spring-web-test-client</artifactId>

      <version>5.3.0</version>

      <scope>test</scope>

</dependency>

Gradle:

testImplementation ‘io.rest-assured:spring-web-test-client:5.3.0’

——————————————————————-


Scala Support

If you’re using Scala you may leverage the scala-support module. For this to work you need to depend on the scala-support module:

——————————————————————-

SBT:

libraryDependencies += “io.rest-assured” % “scala-support” % “5.3.0”

Maven:

<dependency>

    <groupId>io.rest-assured</groupId>

    <artifactId>scala-support</artifactId>

    <version>5.3.0</version>

    <scope>test</scope>

</dependency>

Gradle:

testImplementation ‘io.rest-assured:scala-support:5.3.0’

——————————————————————-


Kotlin

If you’re using Kotlin then it’s highly recommended to use the Kotlin Extension Module. This modules provides some useful extension functions when working with REST Assured from Kotlin.

——————————————————————-

Maven:

<dependency>

    <groupId>io.rest-assured</groupId>

    <artifactId>kotlin-extensions</artifactId>

    <version>5.3.0</version>

    <scope>test</scope>

</dependency>

Gradle:

testImplementation ‘io.rest-assured:kotlin-extensions:5.3.0’

——————————————————————-

Then import Given from the io.restassured.module.kotlin.extensions package.

If you’re using the Spring MockMvc module please refer to the documentation here on how to use custom Kotlin extension functions for this module.


Java 9

When using Java 9+ and find yourself having problems with split packages you can depend on:

——————————————————————-

<dependency>

   <groupId>io.rest-assured</groupId>

   <artifactId>rest-assured-all</artifactId>

   <version>5.3.0</version>

   <scope>test</scope>

</dependency>

——————————————————————-

instead of just rest-assured.

Reference: 

https://github.com/rest-assured/rest-assured/wiki/GettingStarted#non-maven-users

  

Sample API Test Script 

Let’s create a simple API test to show the effectiveness and simplicity of Rest Assured. Let’s say we have an endpoint that uses a RESTful API to retrieve user data. To make an HTTP GET request to this endpoint and verify the response, we can utilise Rest Assured. Using Behaviour-driven Development (BDD) which  is a software development technique that has evolved from TDD (Test Driven Development), which is an approach or programming practice where the developers write new code only when the automated test case fails

Gherkin uses a set of special keywords to give structure and meaning to executable specifications. Each keyword is translated to many spoken languages; in this reference we’ll use English.Most lines in a Gherkin document start with one of the keywords.

 

Here is an illustration test script For Get Endpoint :

 

import static io.restassured.RestAssured.*;

public class UserApiTest {

    @Test
    public void getUserDetailsTest() {
        given()
            .baseUri(“https://api.example.com”)
            .pathParam(“userId”, 123)
        .when()
            .get(“/users/{userId}”)
        .then()
            .statusCode(200)
            .body(“name”, equalTo(“John Doe”))
            .body(“email”, equalTo(“johndoe@example.com”));
    }
}

 

In this example, we supply the base URI and the path parameter for the user ID. We next perform an HTTP GET request to the “/users/userId” endpoint and verify that the result has a status code 200. Furthermore, we ensure that the response body contains the expected name and email values. The fluent syntax of Rest Assured enables for short and expressive assertions, making the test script more readable and maintainable.

Here is an illustration test script For POST Endpoint :

 

import static io.restassured.RestAssured.*;

public class UserApiTest {

    @Test
    public void createUserTest() {
        given()
            .baseUri(“https://api.example.com”)
            .contentType(ContentType.JSON)
            .body(“{\”name\”:\”Jane Smith\”,\”email\”:\”janesmith@example.com\”}”)
        .when()
            .post(“/users”)
        .then()
            .statusCode(201)
            .body(“id”, notNullValue())
            .body(“name”, equalTo(“Jane Smith”))
            .body(“email”, equalTo(“janesmith@example.com”));
    }
}

The POST request used in this example to add a new user to the system is explained. The base URI for the API endpoint is set by the given() method. The request body is in JSON format because the contentType is set to JSON. The name and email of the user who is to be created are included in the request body. When() executes the actual request using the chosen HTTP endpoint and method. The response is verified using the then() method. In this instance, we look for a status code of 201 (Created) and verify that the generated ID, name, and email of the newly formed user are present in the response body.

Here is an illustration test script For PUT Endpoint :

 

import static io.restassured.RestAssured.*;

public class UserApiTest {

    @Test
    public void updateUserTest() {
        given()
            .baseUri(“https://api.example.com”)
            .pathParam(“userId”, 123)
            .contentType(ContentType.JSON)
            .body(“{\”name\”:\”Updated Name\”,\”email\”:\”updatedemail@example.com\”}”)
        .when()
            .put(“/users/{userId}”)
        .then()
            .statusCode(200)
            .body(“name”, equalTo(“Updated Name”))
            .body(“email”, equalTo(“updatedemail@example.com”));
    }
} 

 

This example shows how to change a user’s information using a PUT request. The “userId” path parameter’s value is set by the pathParam method to identify the particular user whose information is to be changed. JSON is used as the contentType to specify the request body’s format. The user’s updated name and email are included in the request body. The PUT request is carried out by the when() method, and the response is verified by the then() method. In this instance, we anticipate a status code of 200 (OK) and check to see if the response content accurately matches the new name and email data.

 

Here is an illustration test script For Patch Endpoint :

 

import static io.restassured.RestAssured.*;

public class UserApiTest {

    @Test
    public void patchUserTest() {
        given()
            .baseUri(“https://api.example.com”)
            .pathParam(“userId”, 123)
            .contentType(ContentType.JSON)
            .body(“{\”email\”:\”newemail@example.com\”}”)
        .when()
            .patch(“/users/{userId}”)
        .then()
            .statusCode(200)
            .body(“name”, equalTo(“John Doe”))
            .body(“email”, equalTo(“newemail@example.com”));
    }
} 

This example shows how to utilize a PATCH request to partially change an existing user’s information. The “userId” path parameter’s value is set by the pathParam method to identify the particular user whose information is to be changed. JSON is used as the contentType to specify the request body’s format. In this instance, the user’s changed email address is the only thing in the request body. The PATCH request is carried out by the when() method, and the response is verified by the then() method. We look for a status code of 200 (OK) and confirm that the response body includes both the old and new email addresses.

 

Here is an illustration test script For Delete Endpoint :

 

import static io.restassured.RestAssured.*;

public class UserApiTest {

    @Test
    public void deleteUserTest() {
        given()
            .baseUri(“https://api.example.com”)
            .pathParam(“userId”, 123)
        .when()
            .delete(“/users/{userId}”)
        .then()
            .statusCode(204);
    }
}

 

This example shows how to delete a user from the system using a DELETE request. The “userId” path parameter’s value is set by the pathParam method to specify the user who is to be deleted. The DELETE request is made using the when() method, and the response is verified using the then() method. We anticipate a status code of 204 (No Content), which signifies that the user was successfully erased and that there is no response body, in this situation.

 

Conclusion 

In this blog post, we looked at the setup and usage of the Rest Assured API testing framework. We talked about setting up the project initially, integrating Rest Assured into a Java project, and dealing with project dependencies. Additionally, we offered sample scripts showing how to use Rest Assured for popular HTTP endpoints including GET, POST, PUT, PATCH, and DELETE.

 Through the use of a fluid and expressive syntax, Rest Assured streamlines the API testing procedure. Testers may rapidly get started with Rest Assured and develop useful API tests by following the setup and execution methods described in this blog post.

 We demonstrated using sample scripts how to use Rest Assured to send HTTP requests, set request parameters, and validate responses. Rest Assured offers user-friendly methods to handle each scenario, whether it is retrieving data with GET requests, creating resources with POST requests, changing resources with PUT and PATCH requests, or deleting resources with DELETE requests.

 Testers can develop thorough API tests that confirm the functionality, performance, and accuracy of their APIs by utilizing the capabilities of Rest Assured. Because Rest Assured is so straightforward and adaptable, testers can concentrate on the core of their tests, which speeds up and improves the testing procedure.

 In conclusion, Rest Assured is a strong framework that makes it simple for testers to conduct API testing. Testers can fully utilize Rest Assured for their API testing needs by following the setup and execution instructions provided in this blog article and using the example scripts. With the help of Rest Assured, testers may guarantee the quality, dependability, and conformance of their APIs, resulting in software applications that are robust and perform well.