REST API Testing With Cucumber Using BDD Approach

This Tutorial Explains REST API Testing with Cucumber Using BDD Approach. It Covers Software Installation, Project Setup, TestScript Execution, and Reports.

In this article, we will see how to get started with REST API Testing in BDD style with the Cucumber framework.

Before diving deep into the topic, let us understand the important concepts involved in it.

Let’s Start!!

REST API Testing in BDD Style With Cucumber

Important Concepts In REST API


This is a software architectural style. The full form of REST is Representational State Transfer. It defines a set of constraints to be used for creating Web services. Web services that conform to the REST architectural style are called RESTful web services.

REST API Testing

REST API testing is testing API using 4 major methods i.e. POST, GET, PUT, and DELETE.

REST Template

RestTemplate is an open-source spring framework class that provides a convenient way to test the HTTP based restful web services by providing overloaded methods for the HTTP methods.

Note: To know more about the REST API Testing concept, you can refer to our earlier tutorial ‘REST API Testing with Spring RestTemplate and TestNG’ where we have covered how to perform REST API Testing manually along with the concept of JSON.


BDD is the Behavior-Driven Development approach. This is one of the software development techniques that has emerged from the Test-Driven Development i.e. TDD style.

The principle of BDD testing is that test cases are written in a natural language that is easily readable by the non-programmers as well.


Cucumber is a tool that supports Behavior-driven development

How Does Cucumber Work?

Let’s see how Cucumber works.

Cucumber consists of Feature Files, Step Definition Files, and Runner class.

Feature Files

Feature files are written by your Business Analyst or maybe your Sponsor. These are written in natural language format having specifications described in it and validate that the application’s functions as per the specifications.

These specifications have multiple scenarios or examples mentioned in it. Each scenario is a list of certain steps for Cucumber to work through.

Let us consider a scenario where the user wants to log in to the system.

To verify if this is working as per the specifications, this scenario needs to be described. Here, are the steps to be performed along with the desired outcome as per the specifications.

Just to get an idea, this is how a sample scenario will look like:

Scenario: Login to the system
  Given User launches Login screen
  When User enters username, password and submit 
  Then Login Successful message appears

You can see, each scenario is a kind of list of the steps for Cucumber to work through. For Cucumber to understand the scenarios, they must follow some basic syntax rules, called Gherkin.

Step Definition Files

Step definitions files map each Gherkin step mentioned in a Feature file to the implementation code. This enables Cucumber to execute the action that is required to be performed by the step.

Cucumber framework supports many programming languages to write Step definitions like Java, .net, and Ruby.

Note: In the article ‘REST API Testing with Spring RestTemplate and TestNG’, we have developed the TestNG test project with the Spring template.

Now, we will develop the Test Framework for the same REST service and RestTemplate, but by using Cucumber for behavior-driven development testing style.

Let’s get started with the setup of our automation test framework with Cucumber!

Setting Up Cucumber Test Framework On Windows

#1) Installation

(i) We are going to use Java for step definition development. So, First Download JDK installer for windows from Oracle and install Java on your machine.

(ii) IDE (Integrated Development Environment): I have used Eclipse as an IDE for my Automation Test Suite development. You can download it from Eclipse

(iii) Get Eclipse Plug-in for Cucumber:

Follow these steps in the Eclipse:

  • Select Help -> Install New Software from the menu option.
  • Enter ‘Cucumber Eclipse’ in the search text box.
  • Click on the Install button.

Cucumber Plug-in Installation In Eclipse

Eclipse Marketplace

  • Keep clicking on the Next button till you reach the Review License screen.

Finally, click on the checkbox to accept the License Agreement and click on the Finish button. This will complete the installation. Now, Restart the Eclipse IDE. This is required to take plug-in installation in effect.

(iv) Spring Jars: As we are going to use RestTemplate class that belongs to the spring framework, you need to have spring framework jars. You can download spring jars from the Spring Framework and save it to the local folder. For Example, C:/projectJar

(v) JSON-Simple Jars: We need to perform JSON parsing. Hence, we will use a lightweight JSON-simple API. So, Download JSON-simple-1.1.jar and save it to C:/projectJar

(vi) Cucumber Jars:

You would need the following Cucumber jars, to run the Cucumber project:

  1. cucumber-core
  2. cucumber-java
  3. cucumber-JUnit
  4. cucumber-JVM-deps
  5. cucumber-reporting
  6. gherkin
  7. JUnit
  8. mockito-all
  9. cobertura
  10. cucumber-HTML [For reports in html]

You can download these files using pom.xml file. But, the simplest way is to download these jar files from the Central Repository  and save those jar files to the local folder, For Example, C:/projectJar

Now, with this, we have completed all the necessary installations. So, let us create our BDD Test Automation project.

#2) Project Setup

  • Create File -> New -> Java Project -> Name it as ‘CRUD_Cucumber’.
  • Now, Create a new Java package demo.
  • Configure BuildPath of the project:
    • As you have seen in the earlier section, we have installed Cucumber plug-in, downloaded spring, and JSON-simple jars. So, it’s time to add build path in our project to consume those. For that, create a lib folder in CRUD_Cucumber’ folder and now copy all jars from the C:/projectJar to lib/Cucumber, lib/Spring folder.
    • Right-click on ‘CRUD_Cucumber’-> Build Path -> Configure Build Path.
    • Click on the Libraries tab.
    • Click on Add jars button-> Select all jars from the lib/Cucumber folder and lib/Spring folder. This will add all cucumber jars, spring jars and JSON-simple jar to your project build path.

Your project structure will be displayed as follows in the Eclipse Package Explorer.

Package Structure Of Test Project

Project Structure

#3) Feature File

Now, let us build our feature file DemoFeature.feature having the feature as Performing CRUD operations on employee service.

In our example, I have used one dummy sample REST Service.

This feature file describes the scenarios to perform the CRUD operations i.e. to cover CRUD (Create-Read-Update-Delete).

  • Let’s define the Feature first, in our case, it’s Testing CRUD methods, which can be described as follows.
Feature: Test CRUD methods in Sample Employee REST API testing 
  • Now, this has different Scenarios like Create, Update, Read and Delete the employee record. So have a look at the POST scenario:
Scenario: Add Employee record
  • Describe the prerequisite for the test which is setting the URL of the employee service.
Given I Set POST employee service api endpoint
  • Specify the actual test step of sending a post request.
When I Set request HEADER
And Send a POST HTTP request
  • Now, describe the verification of the response body.
Then I receive valid Response

So, in our feature file, the Scenario will look as follows:

Scenario: Add Employee record 
	Given I Set POST employee service api endpoint
When I Set request HEADER
	And Send a POST HTTP request 
Then I receive valid Response

Similarly, you can write the remaining Scenarios as shown below.



#4) Steps Definition Implementation

For feature steps used in the above scenarios, you need to write programmatic implementations, in this case, it is Java.

A Step Definition is a method written in Java having an expression. It links its method to one or multiple steps. So, when Cucumber executes the steps described in a scenario of the feature file, it first looks for a matching step definition to execute.

For Example, when step definition for Add employee using POST can be written as follows.

For Given step, implementation is written as follows:

@Given("^I Set POST employee service api endpoint$")
	public void setPostEndpoint(){
		addURI = "";
		System.out.println("Add URL :"+addURI);

Similarly, for When step, the following is the definition method:

@When ("^Send a POST HTTP request$")
	public void sendPostRequest(){
		doublename_id = Math.random();
		emp_name = "zozo_"+name_id;//Just to avoid Duplicate Name entry
    String jsonBody"{\"name\":\""+emp_name+"\",\"salary\":\"123\",\"age\":\"23\"}";
		System.out.println("\n\n" + jsonBody);
		HttpEntity<String>entity = new HttpEntity<String>(jsonBody, headers);		
		//POST Method to Add New Employee
		restTemplate = newRestTemplate ();
		response = restTemplate.postForEntity(addURI, entity, String.class);

Now, here is the verification step part i.e. the Then step implementation:

	@Then ("^I receive valid Response$")
	Public void verifyPostResponse(){
		responseBodyPOST = response.getBody();
		// Write response to file
		responseBody = response.getBody().toString();
		System.out.println("responseBody --->" + responseBody);
		// Get ID from the Response object
		employeeId = getEmpIdFromResponse(responseBody);
		System.out.println("empId is :" + employeeId);
		// Check if the added Employee is present in the response body.
		// Check if the status code is 201
		System.out.println("Employee is Added successfully employeeId:"+employeeId);	

Note: Here, we are using the RestTemplate method for Sending request. This is same as the method used in ‘REST API Testing with Spring RestTemplate and TestNG. To know more about Rest Template methods, you can refer to the tutorial.

Thus, your step definition will look as follows.


You can implement the step definitions for the remaining scenarios Update, Read, and Delete Employee in the same way.

#5) Running The Tests

Now, we have completed our scenario and step script development task, so let’s run our tests. For this, we need to write a JUnit runner class.

publicclassRunner {


Here, you need to add the following annotations above the class name:

@RunWith(Cucumber.class): To run as a test runner class for Cucumber.

@CucumberOptions: Here you specify the Features file location and Step definition file location for the Cucumber framework to look into during execution.

features="<path of feature file>"
glue="<path of step defs class>"

Plug-in: This is used to specify different formatting options for the report which gets generated as output.

Hence, your runner class will look like this.


Just right-click on and select the option ‘Run as JUnit Test’. This will display the test execution result as follows.

Junit Tab Output

Junit tab output

You will see the following messages on Console.

Console Output

Console output

#6) Reports

We have seen the result on the console. However, Cucumber provides test results in a more presentable HTML format that can be shared with your stakeholders.

Open target -> cucumber-reports in the browser.

Note: Remember Junit runner class CucucmberOptions?

@CucumberOptions (features="Features",glue={"demo"},plugin={"pretty", "html:target/cucumber-reports"})

Here plugin is the option that we specify for HTML format reports along with the folder.


Now open target\cucumber-reports\index.html page. The report page is the HTML page where you can see the Feature name with Scenarios that got executed successfully.

So, your Report will look as follows.

CucumberTest Result In Html Format

CucumberTest Result in Html format


To conclude this tutorial, let us summarize what we have learned so far.

We saw all the steps from the beginning to set up the BDD Cucumber REST API Test Automation Framework.

In this process we learned the following:

  • For test automation, we selected Java as the programming language.
  • We chose Cucumber as the test framework for creating a Test suite in the Behaviour Driven Development test way.
  • For sending actual HTTP requests to the server, we consumed the Spring framework RestTemplate class.
  • For consuming these APIs, we did the installation of Cucumber plug-in, downloaded the Cucumber dependencies jar files, Spring jars and JSON-simple jar for parser API.
  • We created the Feature file to describe scenarios in plain English, Step Definition file to map Steps and JUnit Runner class to run the Feature file.
  • Finally, we executed the Test Runner class and saw the result on the console in a more presentable and readable HTML format.

In short, this article explained how to get started with the REST API Test automation with Cucumber. We covered setting up our test automation framework right from installation of all essential software, Project Setup, TestScript development till Test execution and viewing generated reports.

This is sufficient for any automation QA to get started with the test automation framework. But if someone wants to understand in detail how does Cucumber functions internally, how does Gherkin language work, then it can be explored on Cucumber.

I hope you are ready to get started with the Testing Of REST API In BDD Style With Cucumber!!