Rest API Test in Cucumber BDD

HOME

Cucumber is not an API automation tool, but it works well with other API automation tools.

There are 2 most commonly used Automation Tools for JVM to test API – Rest-Assured and Karate. In this tutorial, I will use RestAssured for API Testing.

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. REST Assured can be used easily in combination with existing unit testing frameworks, such as JUnit and TestNG.

What is Cucumber?

Cucumber is one such open-source tool, which supports Behavior Driven Development(BDD). In simple words, Cucumber can be defined as a testing framework, driven by plain English. It serves as documentation, automated tests, and development aid – all in one.

In this tutorial, I will explain creating a framework for the testing of Rest API in Cucumber BDD. This framework consists of:

  1. Cucumber
  2. Java 8 or above
  3. JUnit
  4. Maven
  5. RestAssured

Steps to setup Cucumber Test Automation Framework for API Testing using Rest-Assured

  1. Download and Install Java on the system
  2. Download and setup Eclipse IDE on the system
  3. Setup Maven on System
  4. Create a new Maven Project
  5. Create a source folder – src/test/resources to create test scenarios in the Feature file
  6. Add Rest-Assured and Cucumber dependencies to the project
  7. Add Maven Compiler Plugin
  8. Create a feature file under src/test/resources
  9. Create the Step Definition class or Glue Code for the Test Scenario
  10. Create a Cucumber Runner class
  11. Run the tests from JUnit
  12. Run the tests from Command Line
  13. Cucumber Report Generation

Project Structure

Step 1- Download and Install Java

Cucumber and Rest-Assured need Java to be installed on the system to run the tests. Click here to know How to install Java.

Step 2 – Download and setup Eclipse IDE on system

The Eclipse IDE (integrated development environment) provides strong support for Java developers. Click here to know How to install Eclipse.

Step 3 – Setup Maven

To build a test framework, we need to add several dependencies to the project. Click here to know How to install Maven.

Step 4 – Create a new Maven Project

File -> New Project-> Maven-> Maven project-> Next -> Enter Group ID & Artifact ID -> Finish

Click here to know How to create a Maven project

Step 5 – Create source folder src/test/resources to create test scenarios in Feature file

A new Maven Project is created with 2 folders – src/main/java and src/test/java. To create test scenarios, we need a new source folder called – src/test/resources. To create this folder, right-click on your maven project ->select New ->Java and then Source Folder.

Mention the source folder name as src/test/resources and click the Next button. This will create a source folder under your new Maven project as shown in the below image.

Step 6 – Add Rest-Assured and Cucumber dependencies to the project

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

<!-- 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>

<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-junit -->
<dependency>
      <groupId>io.cucumber</groupId>
      <artifactId>cucumber-junit</artifactId>
      <version>6.8.1</version>
      <scope>test</scope>
</dependency>
  
<dependency>
	  <groupId>io.cucumber</groupId>
	  <artifactId>cucumber-java</artifactId>
	  <version>6.8.1</version>
	  <scope>test</scope>
</dependency>

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

Step 7 – Add Maven Compiler Plugin

The compiler plugin is used to compile the source code of a Maven project. This plugin has two goals, which are already bound to specific phases of the default lifecycle:

  • compile – compile main source files
  • testCompile – compile test source files
<build>
     <plugins>
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-compiler-plugin</artifactId>
         <version>3.7.0</version>
         <configuration>
           <source>1.8</source>
           <target>1.8</target>
            <encoding>UTF-8</encoding>          
         </configuration>
       </plugin>                
     </plugins>
</build>

Step 8 – Create a feature file under src/test/resources

Create a folder with name features. Now, create the feature file in this folder. The feature file should be saved with extension .feature. This feature file contains the test scenarios created to test the application. The Test Scenarios are written in Gherkins language in the format of Given, When, Then, And, But.

Below is an example of a Test Scenario where we are using the GET method to get the information from the API.

Feature: Validation of get method

@GetUserDetails
  Scenario Outline: Send a valid Request to get user details

  Given I send a request to the URL to get user details
  Then the response will return status 200 and id <id> and salary <employee_salary> and name "<employee_name>" and age <employee_age> and message "<message>"

Examples:
    |id  |employee_salary|employee_name |employee_age  |message                                  |
    |1   |320800         |Tiger Nixon   |61            |Successfully! Record has been fetched.   |
   

Step 9 – Create the Step Definition class or Glue Code for the Test Scenario

StepDefinition acts as an intermediate to your runner and feature file. It stores the mapping between each step of the scenario in the Feature file. So when you run the scenario, it will scan the stepDefinition file to check matched glue or test code.

import io.restassured.http.ContentType;

import io.restassured.response.ValidatableResponse;

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

import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;

public class API_GETDefinitions {
	

	private ValidatableResponse validatableResponse;

    private String endpoint = "http://dummy.restapiexample.com/api/v1/employee/1";
 
	@Given("I send a request to the URL to get user details")
	public void sendRequest(){
		validatableResponse = given().contentType(ContentType.JSON)
			    .when().get(endpoint).then();   
		
		System.out.println("Response :"+validatableResponse.extract().asPrettyString());
	}
 
 
	@Then("the response will return status {int} and id {int} and salary {int} and name {string} and age {int} and message {string}")
	public void verifyStatus(int statusCode, int id, int emp_Salary, String emp_name, int emp_age, String message ){
		
		validatableResponse.assertThat().statusCode(statusCode);
		
		validatableResponse.assertThat().body("data.id",equalTo(id));
		
		validatableResponse.assertThat().body("data.employee_salary",equalTo(emp_Salary));
		
		validatableResponse.assertThat().body("data.employee_name",equalTo(emp_name));
		
		validatableResponse.assertThat().body("data.employee_age",equalTo(emp_age));
		
		validatableResponse.assertThat().body("message",equalTo(message));		
		
	}
}

In order to use REST assured effectively it’s recommended to statically import methods from the following classes:

io.restassured.RestAssured.*
io.restassured.matcher.RestAssuredMatchers.*
org.hamcrest.Matchers.*

There is another way to perform these assertions. We can use multiple body assertions together.

@Then("the response will return status {int} and id {int} and salary {int} and name {string} and age {int} and message {string}")
	public void verifyStatus(int statusCode, int id, int emp_Salary, String emp_name, int emp_age, String message ){
				

validatableResponse.assertThat().statusCode(statusCode).body("data.id",equalTo(id)).and()
		.body("data.employee_salary",equalTo(emp_Salary)).body("data.employee_name",equalTo(emp_name))
		.body("data.employee_age",equalTo(emp_age)).body("message",equalTo(message));

Step 10 – Create a JUnit Cucumber Runner class to execute the test scenarios

A runner will help us to run the feature file and acts as an interlink between the feature file and StepDefinition Class.

import org.junit.runner.RunWith;

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;

@RunWith(Cucumber.class)

@CucumberOptions(features= {"src/test/resources"}, glue= {"com.example.apidemo"})
public class CucumberRunnerTest {

}

Note:- The name of the Runner class should end with Test otherwise we can’t run the tests using Command-Line.

Step 11 – Run the tests from JUnit

You can execute the test script by right-clicking on TestRunner class -> Run As JUnit.

Step 12 – Run the tests from Command Line

Run the below command in the command prompt to run the tests and to get the test execution report.

mvn test

Step 13 – Cucumber Report Generation

To get Cucumber Test Reports, add cucumber.properties under src/test/resources and add the below instruction in the file.

cucumber.publish.enabled=true

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