Integration of REST Assured with TestNG

HOME

As we know, REST Assured is a Java DSL for simplifying testing of REST based services built on top of HTTP Builder. In this tutorial, I’ll create a Test Framework for the testing of REST API using REST Assured and TestNG as test framework. This framework consists of:-

  1. REST Assured – 4.3.3
  2. Java 8 or above
  3. TestNG – 7.4.0
  4. Maven – 3.8.1

Steps to setup Rest API Test Automation Framework with REST Assured and TestNG

  1. Download and Install Java on system
  2. Download and setup Eclipse IDE on system
  3. Setup Maven
  4. Create a new Maven Project
  5. Add REST Assured and TestNG dependencies to the project
  6. Create a TEST file under src/test/java to write the test code.
  7. Run the tests as TestNG Tests
  8. Run the tests from TestNG.xml
  9. TestNG Report Generation

Detailed Step Description

Step 1- Download and Install Java

Java needs to be present on the system to run the tests. Click here to know How to install Java. To know if Java is installed or not on your machine, type this command in the command line. This command will show the version of Java installed on your machine.

java -version

Step 2 – Download and setup Eclipse IDE on system

The Eclipse IDE (integrated development environment) provides strong support for Java developer which is needed to write Java code. Click here to know How to install Eclipse.

Step 3 – Setup Maven

To build a test framework, we need to add a number of dependencies to the project. It is very tedious and cumbersome process to add each dependency manually. So, to overcome this problem, we use a build management tool. Maven is a build management tool which is used to define project structure, dependencies, build, and test management. Click here to know How to install Maven.

To know if Maven is already installed or not on your machine, type this command in the command line. This command will show the version of Maven installed on your machine.

mvn -version

Step 4 – Create a new Maven Project

Click here to know How to create a Maven project

Below is the Maven project structure. Here,

Group Id – com.example
Artifact Id – RestAssured_TestNG_Demo
Version – 0.0.1-SNAPSHOT
Package – com. example.RestAssured_TestNG_Demo

Step 5 – Add REST Assured and TestNG dependencies to the project

Add below mentioned REST Assured and TestNG dependencies to the project.

<dependencies>
 <!-- https://mvnrepository.com/artifact/org.testng/testng -->
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>7.4.0</version>
      <scope>test</scope>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
   <dependency>
     <groupId>io.rest-assured</groupId>
     <artifactId>rest-assured</artifactId>
     <version>4.3.3</version>
     <scope>test</scope>
    </dependency>
</dependencies>

To create a JSONObject body for the request, we need to add below dependencies to the Test Framework.

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.3</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency> 

Step 6 – Create a TEST file under src/test/java to write the test code.

To know how to create a JSON Request body using JSONObject, please refer this tutorial.

To know more about priority in TestNG, please refer this tutorial.

public class API_Test {

	@Test(description = "To get the details of employee with id 2", priority = 0)
	public void verifyUser() {

		// Given
		given()
		
        // When
		.when()
              .get("http://dummy.restapiexample.com/api/v1/employee/2")
				
         // Then
		 .then()
                .statusCode(200)
                .statusLine("HTTP/1.1 200 OK")
				// To verify booking id at index 3
				.body("data.employee_name", equalTo("Garrett Winters"))
				.body("message", equalTo("Successfully! Record has been fetched."));
	}

	@Test(description = "To create a new employee", priority = 1)
	public void createUser() {

		JSONObject data = new JSONObject();

		data.put("employee_name", "APITest");
		data.put("employee_salary", "99999");
		data.put("employee_age", "30");

		
		// GIVEN
		given()
               .baseUri("http://dummy.restapiexample.com/api")
               .contentType(ContentType.JSON)
               .body(data.toString())

		// WHEN
		.when()
               .post("/v1/create")

		// THEN
		.then()
               .statusCode(200)
               .body("data.employee_name", equalTo("APITest"))
			   .body("message", equalTo("Successfully! Record has been added."));

	}

}

Step 7 – Test Execution through TestNG

Go to Runner class and right click Run As TestNG Test. The tests will run as TestNG tests.

This is how the execution console will look like.

Step 8 – Run the tests from TestNG.xml

Create a TestNG.xml as shown below and run the tests as TestNG. Here, the tests are present in class – com.example.Selenium_TestNGDemo.API_Test.

<?xml version = "1.0"encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "Suite1">
  <test name = "Test Demo">
    <classes>
          <class name = "com.example.Selenium_TestNGDemo.API_Test"/>
     </classes>  
   </test>
</suite>

Step 9 – TestNG Report Generation

After test execution, refresh the project, a new folder with name test-output will be generated. This folder contains the reports generated by TestNG. The structure of folder test-output looks like as shown below.

We are interested in ’emailable-report.html’ report. Open ’emailable-report.html’, as this is a html report open it with browser. Below image shows emailable-report.html.

TestNG also produce “index.html” report and it resides under test-output folder. Below image shows index.html report. This report contains the high level summary of the tests.

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

How To Send A JSON/XML File As Payload To Request using Rest Assured

HOME

In this tutorial, I will explain to pass a JSON or XML file as a payload to the request. This is needed when the payload is static or there is minimal change in the request payload. This can be done by using the body() method which accepts “File” as an argument. This is elaborated in Javadoc.

RequestSpecification body(File body)

This specify file content that’ll be sent with the request. This only works for the POST, PATCH and PUT http method. Trying to do this for the other http methods will cause an exception to be thrown.

Pass JSON file as payload

Step 1 – Create a .json file and write payload in that. Keep the file in “src/test/resources” folder.

Step 2 – Create a File in Java using “File” and pass to body() method.

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

import java.io.File;

import org.junit.Test;

import io.restassured.http.ContentType;
import io.restassured.response.ValidatableResponse;

public class passJsonAsPayload {

	ValidatableResponse validatableResponse;

	@Test
	public void createUser() {

		// Creating a File instance
		File jsonData = new File("src/test/resources/Payloads/jsondemo.json");

		// GIVEN
		given()
               .baseUri("http://dummy.restapiexample.com/api")
               .contentType(ContentType.JSON)
			   .body(jsonData)

		// WHEN
		.when()
              .post("/v1/create")

		// THEN
		.then()
               .assertThat()
               .statusCode(200)
               .body("data.name", equalTo("Json_Test"))
			   .body("message", equalTo("Successfully! Record has been added."))
               .log().all();

	}

}

Similarly, we can pass an XML as a payload to request. The file passed within body() method should be of type .xml.

Congrates. You have learnt how to pass a JSON as a payload to the request. Happy Learning !!

Extraction from JSON in Rest Assured

HOME

In this tutorial, I will explain how can we extract body from JSON Response in Rest Assured. This is needed for the assertion of tests. In t he previous tutorial, I have explained various types of Assertions can be done on JSON Request using Hamcrest.

JsonPath is available at the Central Maven Repository. Maven users add this to the POM.

<!-- https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path -->
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.6.0</version>
</dependency>

If the project is Gradle, add below dependency in build.gradle.

 testImplementation 'com.jayway.jsonpath:json-path:2.6.0'

JsonPath expressions can use the dot–notation.

$.store.book[0].title

or the bracket–notation

$['store']['book'][0]['title']

Below are the most commonly used expressions.

Expression Description
$ The root object or array.
.property Selects the specified property in a parent object.
[‘property’] Selects the specified property in a parent object. Be sure to put single quotes around the property name.Tip: Use this notation if the property name contains special characters such as spaces, or begins with a character other than A..Za..z_.
[n] Selects the n-th element from an array. Indexes are 0-based.
[index1,index2,…] Selects array elements with the specified indexes. Returns a list.
..property Recursive descent: Searches for the specified property name recursively and returns an array of all values with this property name. Always returns a list, even if just one property is found.
* Wildcard selects all elements in an object or an array, regardless of their names or indexes.
[start:end]
[start:]
Selects array elements from the start index and up to, but not including, end index. If end is omitted, selects all elements from start until the end of the array. Returns a list.
[:n] Selects the first n elements of the array. Returns a list.
[-n:] Selects the last n elements of the array. Returns a list.
[?(expression)] Selects all elements in an object or array that match the specified filter. Returns a list.
[(expression)] Script expressions can be used instead of explicit property names or indexes. An example is [(@.length-1)] which selects the last item in an array. Here, length refers to the length of the current array rather than a JSON field named length.
@ Used in filter expressions to refer to the current node being processed.

Below is the sample JSON which I am using for extraction examples.

String jsonString = {
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

To extract all books present in store:-

        String allBooks = JsonPath.read(jsonString, "$..*").toString();
		System.out.println("--------------- All books in the store --------------");
		System.out.println(allBooks);

Below are examples which shows how to extract different nodes from a JSON Body. I have used above JSON Body for these examples.

        // All bicycles in the store
		String allBicycles = JsonPath.read(jsonString, "$..bicycle").toString();
		System.out.println("--------------- All bicycles in the store ---------------");
		System.out.println(allBicycles);

		// The number of books
		String noOfBooks = JsonPath.read(jsonString, "$..book.length()").toString();
		System.out.println("--------------- The number of books ---------------");
		System.out.println(noOfBooks);

		// The authors of all books
		String authors = JsonPath.read(jsonString, "$.store.book[*].author").toString();
		System.out.println("--------------- Author of all Books ---------------");
		System.out.println(authors);

		// All authors
		String allAuthors = JsonPath.read(jsonString, "$..author").toString();
		System.out.println("--------------- All Authors ---------------");
		System.out.println(allAuthors);

		// All details of the store
		String store = JsonPath.read(jsonString, "$.store.*").toString();
		System.out.println("--------------- All details of the store ---------------");
		System.out.println(store);

		// Price of store
		String storePrice = JsonPath.read(jsonString, "$.store..price").toString();
		System.out.println("--------------- price of store ---------------");
		System.out.println(storePrice);

Below are the examples where I have extracted specific book (nodes) from the JSON body.

	    // Third book
		String thirdBook = JsonPath.read(jsonString, "$..book[2]").toString();
		System.out.println("--------------- third book ---------------");
		System.out.println(thirdBook);

		// first Last Book
		String firstLastBook = JsonPath.read(jsonString, "$..book[-1]").toString();
		System.out.println("--------------- first Last Book ---------------");
		System.out.println(firstLastBook);

		// first two Books
		String firstTwoBooks = JsonPath.read(jsonString, "$..book[0,1]").toString();
		System.out.println("--------------- first Two Books ---------------");
		System.out.println(firstTwoBooks);

		// books from index 0 (inclusive) until index 2 (exclusive)
		String booksRange = JsonPath.read(jsonString, "$..book[:2]").toString();
		System.out.println("--------------- books from index 0 (inclusive) until index 2 (exclusive) ---------------");
		System.out.println(booksRange);

		// All books from index 1 (inclusive) until index 2 (exclusive)
		String booksRange1 = JsonPath.read(jsonString, "$..book[1:2]").toString();
		System.out.println("------------ All books from index 1 (inclusive) until index 2 (exclusive) -----------");
		System.out.println(booksRange1);

		// Book number one from tail
		String bottomBook = JsonPath.read(jsonString, "$..book[1:]").toString();
		System.out.println("--------------- Book number one from tail ---------------");
		System.out.println(bottomBook);

Filters are logical expressions used to filter arrays. Below are the examples of a JSONPath expression with the filters.

       // All books in store expensive than 10
		String expensiveBook = JsonPath.read(jsonString, "$.store.book[?(@.price > 10)]").toString();
		System.out.println("--------------- All books in store costlier than 10 ---------------");
		System.out.println(expensiveBook);

		// All books in store that are not "expensive"
		String notExpensiveBook = JsonPath.read(jsonString, "$..book[?(@.price <= $['expensive'])]").toString();
		System.out.println("--------------- All books in store that are not expensive ---------------");
		System.out.println(notExpensiveBook);

		// All books in store that are equal to price 8.95
		String comparePrice = JsonPath.read(jsonString, "$.store.book[?(@.price == 8.95)]").toString();
		System.out.println("--------------- All books in store that are not expensive ---------------");
		System.out.println(comparePrice);

		// All books matching regex (ignore case)
		String regxExample = JsonPath.read(jsonString, "$..book[?(@.author =~ /.*REES/i)]").toString();
		System.out.println("--------------- All books matching regex (ignore case) ---------------");
		System.out.println(regxExample);

		// All books with price equal to mentioned list of prices
		String priceList = JsonPath.read(jsonString, "$..book[?(@.price in ['12.99', '8.99'])]").toString();
		System.out.println("--------------- All books with price equal to mentioned list of prices ---------------");
		System.out.println(priceList);

		// All books with price NOT equal to mentioned list of prices
		String excludePriceList = JsonPath.read(jsonString, "$..book[?(@.price nin ['12.99', '8.99'])]").toString();
		System.out.println("---------- All books with price NOT equal to mentioned list of prices ---------");
		System.out.println(excludePriceList);

		// All books with specified substring (case-sensitive)
		String substringExample = JsonPath.read(jsonString, "$..book[?(@.author contains 'Melville')]").toString();
		System.out.println("--------------- All books with specified substring (case-sensitive) ---------------");
		System.out.println(substringExample);

		// All books with an ISBN number
		String specificBook = JsonPath.read(jsonString, "$..book[?(@.isbn)]").toString();
		System.out.println("--------------- All books with an ISBN number ---------------");
		System.out.println(specificBook);

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Assertion of JSON in Rest Assured using Hamcrest

HOME

What is Assertion?

Assertion is a way to verify that the expected result and the actual result matches or not in the test case.  A test is considered successful ONLY if it is completed without throwing any exception. If the current value and the expected value match then the assertion passes and when the assertion passes nothing happens. But when an assertion fails it will fail the test case.

There are various ways to perform assertions in API Testing. For API Testing, we are using Rest Assured which uses either Hamcrest or JUnit assertions. We are going to discuss Hamcrest Assertions here.

What is Hamcrest?

Hamcrest is a framework for writing matcher objects allowing ‘match’ rules to be defined declaratively. We do not need to add Hamcrest depdendency explicitly as Rest-Assured 4.3.3 version include by itself. To know more about Hamcrest, please refer this link.

Below is an example of JSON Response. I will perform various assertions on this JSON Response.

To use hamcrest assertion please import the Matchers class static member.

Number related assertions

  1. equalTo – It checks whether the retrieved number from response is equal to the expected number.
  2. greaterThan – checks extracted number is greater than the expected number.
  3. greaterThanOrEqualTo – checks whether the extracted number is greater than equal to the expected number.
  4. lessThan – It checks whether the retrieved number from response is lesser than to the expected number.
  5. lessThanOrEqualTo – It checks whether the retrieved number from response is lesser than or equal to the expected number.

Below assertions are imported from package shown below:-

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.lessThan;

Below are the examples to show the use of number related assertions.

public class HamcrestExample {

	public String endpoint = "https://restful-booker.herokuapp.com/booking/1";

	@Test
	public void numberAssertions() {
		RestAssured.given().contentType(ContentType.JSON)
                   .when().get(endpoint).then()
                   .body("totalprice", equalTo(813));

		RestAssured.given().contentType(ContentType.JSON)
                   .when().get(endpoint)
                   .then().body("totalprice",greaterThan(500));

		RestAssured.given().contentType(ContentType.JSON)
                   .when().get(endpoint)
                   .then().body("totalprice",greaterThanOrEqualTo(500));

		RestAssured.given().contentType(ContentType.JSON)
                   .when().get(endpoint)
                   .then().body("totalprice",lessThan(1000));

		RestAssured.given().contentType(ContentType.JSON)
                   .when().get(endpoint)
                   .then().body("totalprice",lessThanOrEqualTo(1000));

	}
}

String related Assertions

  1. equalTo – It checks whether the extracted string from JSON is equal to the expected string.
  2. equalToIgnoringCaseIt checks whether the extracted string from JSON is equal to the expected string without considering the case (small or capital).
  3. equalToIgnoringWhiteSpace – It checks whether the extracted string from JSON is equal to the expected string by considering the white spaces.
  4. containsString – It checks whether the extracted string from JSON contains the expected string as a substring.
  5. startsWith It checks whether the extracted string from JSON is starting with a given string or character.
  6. endsWith It checks whether the extracted string from JSON is ending with a given string or character.

Below assertions are imported from package shown below:-

import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.equalToIgnoringCase;
import static org.hamcrest.Matchers.startsWith;
import static org.hamcrest.Matchers.equalToIgnoringWhiteSpace;

Below are the examples to show the use of string related assertions.

public class HamcrestExample {

	public String endpoint = "https://restful-booker.herokuapp.com/booking/1";

	@Test
	public void stringAssertions() {
		RestAssured.given().contentType(ContentType.JSON)
                   .when().get(endpoint)
                   .then().body("firstname",equalTo("Mark"));

		RestAssured.given().contentType(ContentType.JSON)
                   .when().get(endpoint)
                   .then().body("firstname",equalToIgnoringCase("MARk"));

		RestAssured.given().contentType(ContentType.JSON)
                   .when().get(endpoint)
                   .then().body("firstname",containsString("Mark"));

		RestAssured.given().contentType(ContentType.JSON)
                   .when().get(endpoint)
                   .then().body("firstname",startsWith("M"));

		RestAssured.given().contentType(ContentType.JSON)
                   .when().get(endpoint)
                   .then().body("firstname",endsWith("k"));

        RestAssured.given().contentType(ContentType.JSON)
                   .when().get(endpoint)
                   .then().body("firstname",equalToIgnoringWhiteSpace("   Mark "));


	}
}
  1. nullValue – It checks whether the extracted response from JSON is NULL or Not.
  2. hasKey – It checks whether the extracted map has an expected key.

Below assertions are imported from package shown below:-

import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;

Below are the examples to show the use of collection related assertions.

public class HamcrestExample {

	public String endpoint = "https://restful-booker.herokuapp.com/booking/1";

	@Test
	public void collectionAssertions() {
		RestAssured.given().contentType(ContentType.JSON)
                   .when().get(endpoint)
                   .then().body("totalprice1",is(nullValue()));

		RestAssured.given().contentType(ContentType.JSON)
                   .when().get(endpoint)
                   .then().body("bookingdates",hasKey("checkin"));

	}
}

Not Assertion

The not assertion inverts the meaning of the other assertions. For example, if you want to perform negative assertions, then we can use any assertions with NOT.

Below assertion is imported from package shown below:-

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;

Below are the examples to show the use of negative assertions.

public class HamcrestExample {

	public String endpoint = "https://restful-booker.herokuapp.com/booking/1";

	@Test
	public void negativeAssertions() {
		RestAssured.given().contentType(ContentType.JSON)
                   .when().get(endpoint)
                   .then().body("totalprice",not(equalTo(874)));

	}
}

Multiple Assert Statements

In the below exaple, all 3 asserstions will fail, but it will only execute assertion and first assertion is failed, then other assertions will not be executed.

public class HamcrestExample {

	public String endpoint = "https://restful-booker.herokuapp.com/booking/1";

	@Test
	public void test() {
		RestAssured.given().contentType(ContentType.JSON)
                   .when().get(endpoint).then()
                   .body("firstname", equalTo("Jim")) // will fail
				   .body("lastname", equalTo("Smith")) // will fail
				   .body("totalprice", equalTo(314)); // will fail
	}

}

To execute all the assertions present in the test case we have to combine all the assertion into a single body, just like below. You can see that all the assertions are failed and they are shown in the response.

public class HamcrestExample {

	public String endpoint = "https://restful-booker.herokuapp.com/booking/1";

	@Test
	public void test() {
		RestAssured.given().contentType(ContentType.JSON)
                   .when().get(endpoint).then()
                   .body("firstname", equalTo("Jim"), // will fail																												
				   "lastname", equalTo("Smith"), // will fail
				   "totalprice", equalTo(314)); // will fail
	}

}

I have tried to show the use of few of the most commonly used assertion methods. There are many more methods avilable in Hamcrest package. To know about other methods, write import static org.hamcrest.Matchers and add (.) at the end, it will show the list of all the methods available in Hamcrest.

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

How to create JSON Array Request Body

HOME

In the last tutorial, I have explained  How to test POST JSON Object request using Java Map in Rest Assured . In this tutorial, I will create a Request body using JSON Array in Rest Assured. This request body can be used for POST or PUT operations.

What is JSONArray?

JSONArray represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array.

  1. JSON array can store multiple value types. The values in a JsonArray can be of the following types: JsonObject, JsonArray, JsonString, JsonNumber, JsonValue.TRUE, JsonValue.FALSE, and JsonValue.NULL.

2. The array index begins with 0.

3. The square brackets [ ] are used to declare JSON array.

An API may accept a JSON Array payload as request body. Imagine, we want to add employee details of more than one employee in the below example. In this case, we can pass multiple JSON objects within a JSON array. I have explain 2 ways to create JSON Object – map or JsonObject. Refer any one of the tutorial to get to know about the creation of JSON Object.

To create JSON Array, we need to add a maven dependency as shown below.

<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency>  

JSONObject is imported from package:-

import org.json.JSONObject;

JSONaArray is imported from package:-

import org.json.JSONArray;

Below is an example of JSONArray.

How to create JSONArray Request Body or payload?

  1. Create a JSON Object and add the first employee details.
  2. Create another JSON Object and add second guest details
  3. Create a JSONArray.
  4. Add both JSON Object to JSONArray.

Below is an example of creating a request from JSONArray with multiple JSONObjects.  I am using a logger just to print the JSON body in the Console. 

public class RequestBodyAsJSONArrayDemo {

	@Test
	public void passBodyAsJsonArrayDemo() {

		// JSON Object for first employee
		JSONObject data1 = new JSONObject();

		data1.put("employee_name", "ObjectTest");
		data1.put("profile_image", "test1.png");
		data1.put("employee_age", "30");
		data1.put("employee_salary", "11111");

		// JSON Object for second employee
		JSONObject data2 = new JSONObject();

		data2.put("employee_name", "MapTest");
		data2.put("profile_image", "test2.png");
		data2.put("employee_age", "20");
		data2.put("employee_salary", "99999");

		// Creating JSON array to add both JSON objects
		JSONArray array = new JSONArray();
		array.put(data1);
		array.put(data2);

		// Send the request		
        RestAssured.given()
                          .contentType(ContentType.JSON)
                          .body(array.toString())
                          .log().all()
				
				.when()
                       .post("http://dummy.restapiexample.com/api/v1/create")
				
				.then()
                      .assertThat().statusCode(200)
                      .body("message", equalTo("Successfully! Record has been added."))
				      .log().all();
	}
}

Below is the execution screenshot.

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

How to test POST JSON Object request using Java Map in Rest Assured

HOME

In the last tutorial, I have explained How to test POST request from JSON Object in Rest Assured where request body is built in JSONObject. In this tutorial, I will create a Request body using JSON Object in Rest Assured. 

We can create a JSON Object using a Map in Java. A JSON Object is a key-value pair and can be easily created using a Java Map. A Map in Java also represents a collection of key-value pairs.

I have created a simple Java map and filled it with the values that represent JSON properties.

	@Test
	public void passBodyAsMap() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("employee_name", "MapTest");
		map.put("employee_salary", "99999");
		map.put("employee_age", "30");
		map.put("profile_image", "test.png");
		RestAssured.given()
                          .contentType(ContentType.JSON)
                          .body(map)
                          .log().all()
				
				   .when()
                         .post("http://dummy.restapiexample.com/api/v1/create")
				
				   .then()
                         .assertThat().statusCode(200)
                         .body("data.employee_name", equalTo("MapTest"))
				         .body("data.employee_age", equalTo("30"))
                         .body("data.employee_salary", equalTo("99999"))
				         .body("message", equalTo("Successfully! Record has been added.")).log().all();
	}

The Request body as well as response body will look as shown below:-

Above one is a simple JSON Request Body. Lets take an example of Complex Request Body or nested Request Body as shown below.

@Test
	public void passBodyAsMultipleMap() {
		// First JSON Object using Hash Map
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("employee_name", "MapTest");
		data.put("profile_image", "test.png");
		// Second JSON Object using Hash Map
		Map<String, String> msg = new HashMap<String, String>();
		msg.put("updated_message", "Details of New Resource");
		msg.put("employee_age", "30");
		data.put("details", msg);
		data.put("employee_salary", "99999");
		RestAssured.given().contentType(ContentType.JSON).body(data).log().all()
				// WHEN
				.when().post("http://dummy.restapiexample.com/api/v1/create")
				// THEN
				.then().assertThat().statusCode(200).body("data.employee_name", equalTo("MapTest"))
				.body("data.details.updated_message", equalTo("Details of New Resource"))
				.body("data.details.employee_age", equalTo("30")).body("data.employee_salary", equalTo("99999"))
				.body("message", equalTo("Successfully! Record has been added.")).log().all();
	}
}

The Request body as well as response body will look as shown below image. First part is the body of request and second part is the response provided by API.

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

How to test POST request from JSON Object in Rest Assured

HOME

In the last tutorial, I have explained How to test POST Request using Rest Assured where request body is in String Format. In this tutorial, I will create a Request body using JSON Object in Rest Assured. This request body can be used for POST or PUT operations.

First, setup a basic Rest Assured Maven Project by clicking here and Gradle project by clicking here.

In the previous post, you must have observed that I had hard-coded the JSON request body in a string format. It is not a good practice if you have the dynamic payload or want to create a payload at run time or parameterized one. It is always recommended to create a payload in such a way that you can easily maintain, manage, update, and retrieve values from it. This can be achieved by JSONObject or JSONArray.

JSONObject is an unordered collection of key and value pairs, resembling Java’s native Map implementations. JSON stores data as a key-value pair. Key is left side and value is the right side and a semicolon is used to separate both. One key-value pair is separated from another key-value pair using comma (,).

The internal form is an object having to get and opt methods for accessing the values by name and put methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object.

To create a request body using JSON Object, we need to add a maen dependency.

<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency>   

JSONObject is imported from package:-

import org.json.JSONObject;

JSONObject exposes an API similar to Java’s Map interface. Below is an example of creating a request from JSON Object. Here, Id is auto-generated attribute. We are using the put() method and supply the key and value as an argument. I am using a logger just to print the JSON body in the Console. 

@Test
	public void passBodyAsJsonObject() {

		JSONObject data = new JSONObject();

		data.put("employee_name", "MapTest");
		data.put("profile_image", "test.png");
		data.put("employee_age", "30");
		data.put("employee_salary", "11111");

		
		RestAssured.given()
                      .contentType(ContentType.JSON)
                      .body(data.toString())
                      .log().all()
			
				  .when()
                      .post("http://dummy.restapiexample.com/api/v1/create")
				
				  .then()
                       .assertThat().statusCode(200)
                       .body("data.employee_name", equalTo("MapTest"))
				       .body("data.employee_age", equalTo("30"))
                       .body("data.employee_salary", equalTo("11111"))
				       .body("data.profile_image", equalTo("test.png"))
				       .body("message", equalTo("Successfully! Record has been added."))
                       .log().all();

	}

The Request body will look as shown below:-

The texts produced by the toString() methods strictly conform to the JSON syntax rules.

 .body(data.toString())

Above one is a simple JSON Request Body. Lets take an example of Complex Request Body or nested Request Body.

We need to create two JSONObject here. One will hold overall key-value pairs and another JSONObject will hold only employee_details key-value pairs. 

Below is the example which shows how to create a complex JSON request body using JSONObject.

@Test
	public void passBodyAsJsonObjectDemo() {
        
        //First JSONObject
		JSONObject data = new JSONObject();

		data.put("profile_image", "test.png");
        
        //Second JSONObject
		JSONObject detail = new JSONObject();

		detail.put("updated_message", "Details of New Resource");
		detail.put("employee_age", "30");

		data.put("employee_details", detail);

		data.put("employee_name", "MapTest");
		data.put("employee_salary", "11111");

		
		RestAssured.given()
                         .contentType(ContentType.JSON)
                         .body(data.toString())
                         .log().all()
				
				    .when()
                          .post("http://dummy.restapiexample.com/api/v1/create")
				
				    .then()
                           .assertThat().statusCode(200)
                           .body("data.employee_name", equalTo("MapTest"))
				           .body("data.employee_details.employee_age", equalTo("30"))
				           .body("data.employee_details.updated_message", equalTo("Details of New Resource"))
				           .body("data.employee_salary", equalTo("11111")).body("data.profile_image", equalTo("test.png"))
				          .body("message", equalTo("Successfully! Record has been added."))
                          .log().all();
	}
}

The Request body will look as shown below:-

We are done. Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

How to test DELETE in Rest Assured

HOME

In the last tutorial, I have explained How to test PUT Request using Rest Assured. In this tutorial, I will automate a DELETE Request using Rest Assured. I will verify the status code, line of Status, and content of the Response.

To setup a basic Rest Assured Maven Project, click here and Gradle project, click here.

What is DELETE Method?

An HTTP DELETE method is used to delete an existing resource from collection of resources. The DELETE method requests the origin server to delete the resource identified by the Request-URI. On successful deletion of resource, it returns  200 (OK) and 204 (No Content) status code. It may return as 202 (Accepted) status code if request is queued. . To know more about Rest API, please click here.

Below are the steps to test a DELETE Request using Rest Assured:

The steps to test the DELETE request is similar to any API request, like GET, POST, PUT. To know about the steps and various imports used in the below example in detail, please refer to the tutorial for POST Request.

Let’s see existing details of a Employee ID 3 using Postman:

Let’s write DELETE request in REST Assured in Non BDD Format for id 3:

public class Delete_NonBddDemo {

	RequestSpecification requestSpecification;
	Response response;
	ValidatableResponse validatableResponse;

	@Test
	public void deleteUser() {

		RestAssured.baseURI = "http://dummy.restapiexample.com/api";

		// Create a request specification
		requestSpecification = RestAssured.given();

		// Calling DELETE method
		response = requestSpecification.delete("/v1/delete/3");

		// Let's print response body.
		String resString = response.prettyPrint();

		/*
		 * To perform validation on response, we need to get ValidatableResponse type of
		 * response
		 */
		validatableResponse = response.then();

		// Get status code
		validatableResponse.statusCode(200);

		// It will check if status line is as expected
		validatableResponse.statusLine("HTTP/1.1 200 OK");

		// Check response - message attribute
		validatableResponse.body("message", equalTo("Successfully! Record has been deleted"));

	}
}

Let’s write DELETE request in REST Assured in BDD Format:

public class Delete_BDDDemo {

	ValidatableResponse validatableResponse;

	@Test
	public void deleteUser() {

		
	validatableResponse = given()
                                .baseUri("http://dummy.restapiexample.com/api/v1/delete/3")
				                .contentType(ContentType.JSON)
                         .when()
                                .delete()
				         .then()
                                .assertThat().statusCode(200)
                                .body("message", equalTo("Successfully! Record has been deleted"));

		System.out.println("Response :" + validatableResponse.extract().asPrettyString());

	}

}

We are done. Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

How to test PUT Request using Rest Assured

HOME

In the last tutorial, I have explained How to test POST Request using Rest Assured. In this tutorial, I will automate a PUT Request using Rest Assured. I will verify the status code, line of Status, and content of the Response.

To setup a basic Rest Assured Maven Project, click here and Gradle project, click here.

What is PUT Method?

The HTTP PUT API is primarily used to update existing resource. If the resource does not exist, then API may decide to create a new resource or not (Depends on API development). If a new resource has been created by the PUT API, the origin server MUST inform the user agent via the HTTP response code 201 (Created) response and if an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request. To know more about Rest API, please click here.

Below are the steps to test a PUT Request using Rest Assured:

The steps to test the PUT request is similar to POST request. The only difference is that in POST we send a request to create a new resource whereas here we have a resource and I will update the detail of the already existing resource. To know about the steps and various imports used in the below example, please refer to the tutorial for POST Request.

Below is the response received for Employee with id 2.

I want to change the employee_salary to 99999. Below is the example for the test to update employee_salary.

public class PUT_NonBDDDemo {

	RequestSpecification requestSpecification;
	Response response;
	ValidatableResponse validatableResponse;

	@Test
	public void updateUser() {

		String jsonString = "{\"id\": 2,\r\n" 
                          + "        \"employee_name\": \"Garrett Winters\",\r\n"
				          + "        \"employee_salary\": 99999,\r\n"
                          + "        \"employee_age\": 63,\r\n"
				          + "        \"profile_image\": \"\"}";

		RestAssured.baseURI = "http://dummy.restapiexample.com/api/v1/update/2";

		// Create a request specification
		requestSpecification = RestAssured.given();

		// Setting content type to specify format in which request payload will be sent.
		requestSpecification.contentType(ContentType.JSON);

		// Adding body as string
		requestSpecification.body(jsonString);

		// Calling PUT method
		response = requestSpecification.put();

		// Let's print response body.
		String responseString = response.prettyPrint();

		/*
		 * To perform validation on response, we need to get ValidatableResponse type of
		 * response
		 */
		validatableResponse = response.then();

		// Get status code
		validatableResponse.statusCode(200);

		// It will check if status line is as expected
		validatableResponse.statusLine("HTTP/1.1 200 OK");

		// Check response - name attribute
		validatableResponse.body("data.employee_salary", equalTo(99999));

		// Check response - message attribute
		validatableResponse.body("message", equalTo("Successfully! Record has been updated."));

	}
}

Now, let us convert the same test in BDD format. In the below example, in the first part we have retrived the details of employee with id 2 and in second part we have updated the value of employee_salary to 99999.

@Test
	public void updateUser() {

	// To get the detail of employee with id 2
	validatableResponse = given()
                              .baseUri("http://dummy.restapiexample.com/api/v1/employee/2")
				              .contentType(ContentType.JSON)
                          .when()
                               .get()
                          .then()
                               .assertThat().statusCode(200);

		System.out.println("Response :" + validatableResponse.extract().asPrettyString());

		String jsonString = "{\"id\": 2,\r\n" 
                  + "        \"employee_name\": \"Garrett Winters\",\r\n"
				  + "        \"employee_salary\": 99999,\r\n"
                  + "        \"employee_age\": 63,\r\n"
				  + "        \"profile_image\": \"\"}";

	// Update employee_salary
	validatableResponse1 = given()
                               .baseUri("http://dummy.restapiexample.com/api/v1/update/2")
				               .contentType(ContentType.JSON)
                               .body(jsonString)
                           .when()
                               .put()
                           .then()
                               .assertThat().statusCode(200)
                              .body("data.employee_salary", equalTo(99999))
				              .body("message", equalTo("Successfully! Record has been updated."));
		
       System.out.println("Response :" + validatableResponse1.extract().asPrettyString());

	}

}

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

How to test POST Request using Rest Assured

HOME

In the last tutorial, I have explained How to test GET Request using Rest Assured. In this tutorial, I will automate a POST Request using Rest Assured. I will verify the status code, line of Status, and content of the Response. To setup a basic Rest Assured Maven Project, click here and Gradle project, click here.

What is POST Method?

An HTTP POST method is used to create a new resource in the collection of resources with a request body passed as a JSON/XML or in a different format. If a resource is created successfully by the endpoint or server, it returns a status code 201( Created) , returning a Location header with a link to the newly-created resource with the 201 HTTP status. It may return 200 (OK) and 204 (No Content) status code as well based on how API is developed.

POST is neither safe nor idempotent. It is therefore recommended for non-idempotent resource requests. Making two identical POST requests will most-likely result in two resources containing the same information.

Below are the steps to test a POST Request using Rest Assured:

Step 1 – Specify the base URL to the RESTful web service using RestAssured class.

RestAssured.baseURI = "http://dummy.restapiexample.com/api/v1/create";

Step 2 – Every Request in Rest-Assured library is represented by an interface called RequestSpecification. This interface allows to modify the request, like adding headers or adding authentication details. Use the RestAssured class to generate a RequestSpecification.

requestSpecification = RestAssured.given();

RequestSpecification is imported from package:

import io.restassured.specification.RequestSpecification;

Step 3 – Set the content type to specify format in which request payload will be send to the server. Here, the Content Type is JSON.

requestSpecification.contentType(ContentType.JSON);

contentType is imported from restassured.http package:

import io.restassured.http.ContentType;

Step 4 – Pass Request Body as String.

requestSpecification.body(jsonString);

Step 5 – Send the POST request to the server and recieve the response of the request made by REST Assured. This response contains every details returned by hitting request i.e. response body, response headers, status code, status lines, cookies etc. Response is imported from package:

import io.restassured.response.Response;

Step 6 – To validate response like status code or value , we need to get reference of type ValidatableResponseValidatableResponse is an interface. A validatable response of a request made by REST Assured. ValidatableResponse is imported from package:

import io.restassured.response.ValidatableResponse;

PrettyPrint() – It print the response body if possible and return it as string. Pretty printing is possible for content-types JSON, XML and HTML.

Below is the example of testing a POST request in Non-BDD format where I have used ValidatableResponse for the assertion of status and status line and body of the Response.

public class POST_NonBDDDemo {

	RequestSpecification requestSpecification;
	Response response;
	ValidatableResponse validatableResponse;

	@Test
	public void verifyStatusCode() {

		String jsonString = "{\"name\":\"newapitest\",\"salary\":\"4000\",\"age\":\"29\"}";

		RestAssured.baseURI = "http://dummy.restapiexample.com/api/v1/create";

		// Create a request specification
		requestSpecification = RestAssured.given();

		// Setting content type to specify format in which request payload will be sent.
		requestSpecification.contentType(ContentType.JSON);

		// Adding body as string
		requestSpecification.body(jsonString);

		// Calling POST method
		response = requestSpecification.post();

		// Let's print response body.
		String responseString = response.prettyPrint();

		/*
		 * To perform validation on response, we need to get ValidatableResponse type of
		 * response
		 */
		validatableResponse = response.then();

		// Check status code
		validatableResponse.statusCode(200);

		// It will check if status line is as expected
		validatableResponse.statusLine("HTTP/1.1 200 OK");

		// Check response body - name attribute
		validatableResponse.body("data.name", equalTo("newapitest"));

		// Check response body - message attribute
		validatableResponse.body("message", equalTo("Successfully! Record has been added."));

	}
}

The below image shows the test result of the above test.

Test implemented in BDD Format

  1. equalTo is used for assertion, is imported from a static hamcrest package:
import static org.hamcrest.Matchers.equalTo;

2. given is a static import from package:

import static io.restassured.RestAssured.given;

Below is the example of BDD Test

public class POST_BDDDemo {
	ValidatableResponse validatableResponse;

	@Test
	public void createUser() {

		String json = "{\"name\":\"apitest\",\"salary\":\"5000\",\"age\":\"30\"}";

		// GIVEN
		validatableResponse = given()
				.baseUri("http://dummy.restapiexample.com/api")
				.contentType(ContentType.JSON)
				.body(json)
				
				// WHEN
				.when()
				     .post("/v1/create")
				     
				// THEN
				.then()
				      .assertThat().statusCode(200).body("data.name", equalTo("apitest"))
				      .body("message", equalTo("Successfully! Record has been added."));
		
		System.out.println("Response :" + validatableResponse.extract().asPrettyString());
	}

}

The below image shows the test result of the above test.

The above tests can be used in both Maven and Gradle projects.

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!