How to test GET Request using Rest Assured

HOME

In the last tutorial, I have explained the Setup of the REST Assured Maven Project In Eclipse IDE. In this tutorial, I will automate a GET Request. I will verify the status code, line of Status, and content of the Response.

RestAssured is a class that consists of many static fields and methods. It supports POST, GET, PUT, DELETE, HEAD, PATCH, and OPTIONS requests and verifies the response of these requests.

Below are the steps to test a GET 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/employees";

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.

requestSpecification = RestAssured.given();

RequestSpecification is imported from package:

import io.restassured.specification.RequestSpecification;

Step 3 – Send the 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 = requestSpecification.get();

Response is imported from package:

import io.restassured.response.Response;

Step 4 – To validate response like status code or value , we need to get reference of type ValidatableResponse. ValidatableResponse 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 creating a test in Non-BDD format where I have used ValidatableResponse for the assertion of status and status line of the Response.

public class Get_NonBDDDemo {

	RequestSpecification requestSpecification;
	Response response;
	ValidatableResponse validatableResponse;

	@Test
	public void verifyStatusCode() {

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

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

		// Calling GET method
		response = requestSpecification.get();

		// Let's print response body.
		String resString = response.prettyPrint();
		System.out.println("Respnse Details : " + resString);

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

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

		// Check status line is as expected
		validatableResponse.statusLine("HTTP/1.1 200 OK");

	}
}

If you don’t want to use ValidatableResponse for the assertion, you can use Response from io.restassured .response to get the status code and status line which are asserted using JUnit.Assert.

        // Get status line
		String statusLine = response.getStatusLine();
		Assert.assertEquals(statusLine, "HTTP/1.1 200 OK");

		// Get status code
		int statusCode = response.getStatusCode();
		Assert.assertEquals(statusCode, 200);

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

Below is the test implemented in BDD Format. In this test, I am asserting the data of Employee of Id 2. I have validated the name of the employee as well as the response message.

  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;
public class Get_BDDDemo {


	@Test
	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."));
	}
}

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

Conditional Hooks in Cucumber

HOME

In the previous tutorial, I explained Hooks in Cucumber. In this tutorial, I will explain Condition Hooks in Cucumber.

Hooks can be conditionally selected for execution based on the tags of the scenario. These are called Condition or Tagged Hooks.

Tagged Hooks are much like the scenario hooks, but the only difference is that they are executed before and after the specified tag.

These Tagged hooks will be very specific to the particular tags, so these are not common for all scenarios.

So basically, they can also be run in the following two ways:

  • Before (‘tagName’)
  • After (‘tagName’)

Why do we need Tagged Hooks?

Suppose there are 3 different sets of scenarios. The prerequisites of these scenarios are different, like they have to open different browsers. So, we don’t want to have a common hook for all the scenarios. In this case, we can create a tagged hook to satisfy the requirement of each scenario.

In the below example, there are 3 tags – ChromeBrowser, FireFoxBrowser, and EdgeBrowser. I want to run the hook which has the specified tag for that scenario. For Example, I want @After and @Before hooks related to Chrome Browser should be executed for tag – @ChromeBrowser.

Below is the feature file which has 3 different scenarios.

Feature: Conditional or Tagged Hooks
 
@ChromeBrowser
Scenario: Open Chrome Browser
 
Given I want to open Google Chrome Browser

@FireFoxBrowser
Scenario: Open Firefox Browser
 
Given I want to open Mozilla Firefox Browser

@EdgeBrowser
Scenario: Open Edge Browser
 
Given I want to open Microsoft Edge Browser

Below is the Step Definition for the above feature file.

package com.Cucumber;

import cucumber.api.java.en.Given;

public class ConditionalHooksExampleDefinitions {
	
	@Given("I want to open Google Chrome Browser")
	public void chrome() throws Throwable {
	    System.out.println("I want to open Google Chrome Browser");
	}

	@Given("I want to open Mozilla Firefox Browser")
	public void firefox() throws Throwable {
		System.out.println("I want to open Mozilla Firefox Browser");
	}

	@Given("I want to open Microsoft Edge Browser")
	public void edge() throws Throwable {
		System.out.println("I want to open Microsoft Edge Browser");
	}

}

Hooks can be defined in the same class or different. I have defined Hooks in a separate class.

package com.Cucumber;

import cucumber.api.java.After;
import cucumber.api.java.Before;

public class Hooks {
	
	@BeforeStep
    public void beforeStep(){
        System.out.println("@@@@@@@@@@@@@@@ Before Step @@@@@@@@@@@@@@@@@");
    }
	
	@AfterStep
    public void afterStep(){
        System.out.println("@@@@@@@@@@@@@@@@  After Step @@@@@@@@@@@@@@@@");
    }
	
	@Before("@ChromeBrowser")
    public void beforeGoogle(){
        System.out.println("******* before Chrome *******");
    }
	
	@Before("@FireFoxBrowser")
    public void beforeFirefox(){
        System.out.println("$$$$$$$$$$ before FireFox $$$$$$$$$$");
    }

	@Before("@EdgeBrowser")
    public void beforeEdge(){
		System.out.println("============ before Edge =============");
    }
	
	@After("@ChromeBrowser")
    public void afterGoogle(){
        System.out.println("********* After Google *********");
    }

	@After("@FireFoxBrowser")
    public void afterFireFox(){
		System.out.println("$$$$$$$$$$$ After FireFox $$$$$$$$$$");
    }

	@After("@EdgeBrowser")
    public void afterEdge(){
        System.out.println("============ After Edge ==============");
    }

}

There is no change in the Test Runner Class.

package com.Cucumber;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(monochrome = true, plugin = "pretty", features = "src/test/resources/features/ConditionalHooksExample.feature", tags = {
		"" })
public class MyRunner {

}

The execution Result looks like something below

  1. At the start of execution, @Before(“@ChromeBrowser”) {Scenario Hook} is executed.
  2. After that @BeforeStep (Step Hook) hook is executed.
  3. The given statement of the @ChromeBrowser tag is executed in the third step.
  4. The fourth step is to execute @AfterStep.
  5. Now, at the last, the @After(“@ChromeBrowser”) hook is executed. Similarly, the same sequence is followed for FireFox and Edge Scenarios.

Run Cucumber Test from Maven Command Line

HOME

To have a successful and effective implementation of a test framework, it is always advisable that the test framework supports test execution in multiple ways.
The 2 most commonly used ways to execute tests in Cucumber Framework are by running the tests using JUnit and Maven.

To execute tests using JUnit, we need to create a JUnit Test Runner. Whereas, we need a Maven project to execute Cucumber tests from Command-Line.

Create a Maven project and add the below-mentioned dependencies to your Maven project.

  <dependencies>
  
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
 
 <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
    <dependency>
      <groupId>io.cucumber</groupId>
      <artifactId>cucumber-java</artifactId>
      <version>6.8.1</version>
    </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>

<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.141.59</version>
    </dependency>

<!-- https://mvnrepository.com/artifact/org.assertj/assertj-core -->
    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-core</artifactId>
      <version>3.10.0</version>
      <scope>test</scope>
     </dependency>

 </dependencies>
 
  <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>
   
</project>

Run Test from Command Line

1. Open the command prompt and change the directory to the project location where pom.xml is present.

cd C:\Users\Vibha\eclipse-workspace-test\demo

2. All feature files should be in src/test/resources and create the Cucumber Runner class as CucumberRunnerTest.
Note:- The Runner class name should end with Test to execute the tests from Command Line
Run the following command in the command prompt:

mvn test

mvn test runs Cucumber Features using Cucumber’s JUnit Runner. The @RunWith (Cucumber.class) annotation on the TestRunner class tells JUnit to start Cucumber. Cucumber runs time parses the command-line options to know what feature to run, where the Glue Code lives, what plugins to use, and so on.

3. The below screenshot shows that CucumberRunnerTest class is triggered.

4. The below screenshot shows the build success output.

Overriding Cucumber Options

Cucumber provides several options that can be passed to on the command line.

1. Running Scenarios using Tags from Command Line

If you are using Maven and want to run a subset of scenarios tagged with @ValidCredentials.

mvn test -Dcucumber.filter.tags="@ValidCredentials"

There is one more way to execute Cucumber tests with tags

mvn test -Dcucumber.options="--tags @ValidCredentials"

2. Running a Feature file from Command Line

Suppose you want to run a single Feature File from the command line, then use the below syntax

mvn test -Dcucumber.options="src/test/resources/features/CucumberTagsExample.feature"

3. Creating Cucumber Report from Command Line

If we want to generate a different report, then we can use the following command and see the JUnit report generate at the location mentioned:

mvn test -Dcucumber.options="--plugin junit:target/cucumber-reports/cucumberReport.xml

4. Passing multiple Parameter from Command Line

If we want to pass more than one parameter, then we can use the following command

mvn test -Dcucumber.options="src/test/resources/features/CucumberTagsExample.feature" -Dcucumber.filter.tags="@InValidCredentials"

5. Running a Scenario without a tag from Command Line

If we want to run a single Scenario from the command line and no tag is assigned to that scenario, this is how we specify

 mvn test -Dcucumber.options="src/test/resources/features/CucumberTagsExample.feature:12"

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

In the next tutorial, I explained to run Cucumber Gradle tests from Command Line.

Cucumber Tutorial – Cucumber Reports

HOME

The previous tutorial is all about  JUnit Test Runner. In this tutorial, will show you how to generate reports in Cucumber. 

Cucumber with JUnit gives us the capability to generate reports in the form of HTML, XML, JSON & TXT. Cucumber frameworks generate very good and detailed reports, which can be share with all stakeholders. 

Let’s generate the Cucumber Report

Step 1 − Create a Maven project named MyCucumberProject in Eclipse.

Step 2 − Create a feature file named MyHoliday.feature under src/test/resources

Step 3 − Create a StepDefinition named MyHolidayDefinitions.java under src/test/java

Step 4 − Create a TestRunner class under src/test/resources

Step 5 − Run JUnit TestRunner class by right click Run As -> JUnit

Write the following code for Feature File

Feature: Book Flight and Hotel for Vacation

@BookOneWayFlight
Scenario: Book Flight for one way trip

  Given I live in Dublin with 2 adults and 2 kids
  And I want to book one way flight ticket from Dublin to London on 22nd Jan 2020
  When I search online
  Then TripAdvisor should provide me options of flights on 22nd Jan 2020
  And Cost of my flight should not be more than 50 Euro per person
  And Tickets should be refundable
 
@BookHotel
Scenario: Book Hotel for one the trip

  Given I need 1 room with 2 double beds
  And I want to book hotel from 22nd Jan 2020 to 25th Jan 2020
  When I search online
  Then TripAdvisor should provide me options of hotels for time period of 22nd Jan 2020 to 25th Jan 2020
  And Fare of my room should not be more than 200 Euro per night
  And Breakfast should be included in the room fare

Below is the full program, which shows the step definition of above mentioned feature 

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

public class MyHolidayDefinitions {

          @Given("^I live in Dublin with 2 adults and 2 kids$")
          public void needFlight() {
                   System.out.println("I live in Dublin with 2 adults and 2 kids");
          }

          @Given("^I need 1 room with 2 double beds$")
          public void needRoom() {
                   System.out.println("I need 1 room with 2 double beds");
          }

          @When("^I search online$")
          public void onlineSearch() {
                   System.out.println("I search online");
          }

          @Then("^TripAdvisor should provide me options of flights on 22nd Jan 2020$")
          public void searchFlightInTripAdvisor() {
                   System.out.println("TripAdvisor should provide me options of flights on 22nd Jan 2020");
          }

         @Then("^Cost of my flight should not be more than 50 Euro per person$")
          public void flightFare() {
                   System.out.println("Cost of my flight should not be more than 50 Euro per person");
          }

          @Then("^TripAdvisor should provide me options of hotels for time period of 22nd Jan 2020 to 25th Jan 2020")
          public void searchRoomInTripAdvisor() {
                   System.out.println(
                                      "TripAdvisor should provide me options of hotels for time period of 22nd Jan 2020 to 25th Jan 2020");
          }

          @And("^I want to book one way flight ticket from Dublin to London on 22nd Jan 2020$")
          public void ticketType() {
                   System.out.println("I want to book one way flight ticket from Dublin to London on 22nd Jan 2020");
          }

          @And("^I want to book hotel from 22nd Jan 2020 to 25th Jan 2020$")
          public void stayDuration() {
                   System.out.println("I want to book hotel from 22nd Jan 2020 to 25th Jan 2020");
          }

          @And("^Fare of my room should not be more than 200 Euro per night$")
          public void roomFare() {
                   System.out.println("Fare of my room should not be more than 200 Euro per night");
          }

          @And("^Breakfast should be included in the room fare$")
          public void includeBreakfast() {
                   System.out.println("Breakfast should be included in the room fare");
          }

          @And("^Tickets should be refundable$")
          public void refunableTicket() {
                   System.out.println("Tickets should be refundable");
          }
}

Cucumber HTML Reports

For HTML reports, add html:target/cucumber-reports to the @CucumberOptions plugin option.

import org.junit.runner.RunWith;

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

@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/resources/Feature/MyHoliday.feature", 
plugin = { "pretty","html:target/cucumber-reports" }, tags = { "" })

public class TestRunner {
}

We have specified the path of the Cucumber report, which we want it to generate it under the target folder. This will generate an HTML report at the location mentioned in the formatter

HTML Report Output

Cucumber Json Reports

For Json reports, add json:target/cucumber-reports/Cucumber.json to the @CucumberOptions plugin option.

import org.junit.runner.RunWith;

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

@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/resources/Feature/MyHoliday.feature", 
plugin = { "pretty","json:target/cucumber-reports/Cucumber.json" }, tags = { "" })

public class TestRunner {
}

JSON Report Output

Cucumber JUNIT XML Report

For JUNIT reports, add junit:targe/cucumber-reports/Cucumber.xml to the @CucumberOptions plugin option.

import org.junit.runner.RunWith;

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

@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/resources/Feature/MyHoliday.feature", 
plugin = { "pretty","junit:target/cucumber-reports/Cucumber.xml" }, tags = { "" })

public class TestRunner { 
}

Cucumber JUnit XML Report

Cucumber Tutorial – What is Feature File in Cucumber

HOME

In the previous tutorial, we discussed How Cucumber can be setup with Eclipse. In this tutorial, we will discuss the Feature files. 

What is Feature File?

Cucumber tests are grouped into features. A Feature file is one in which we store a description of the features and scenarios to be tested. It is used to provide a high-level description of test scenarios and to group related scenarios. A Feature File is an entry point to the Cucumber tests.

The first keyword in the Feature file is the Feature keyword, followed by: and short text that describes the feature.

You can add free-form text underneath the Feature to add more description.

These description lines are ignored by Cucumber at runtime, but are available for reporting (They are included by default in HTML reports).

The name and the optional description have no special meaning to Cucumber. Their purpose is to provide a place for you to document important aspects of the feature, such as a brief explanation and a list of business rules (general acceptance criteria).

The free format description for Feature ends when you start a line with the keyword Example or Scenario Outline (or their alias keywords).

You can place tags above Feature to group related features, independent of your file and directory structure.

A simple feature file consists of the following keywords/parts −

  • FeatureFile Name – Name of the feature under test. For example, here is MyHoliday.feature
  • Feature − Describe the feature under test, like here “Book flight ticket”
  • Scenario − What is the test scenario we want to test
  • Given − Prerequisite before the test steps get executed.
  • When − Specific condition which should match in order to execute the next step.
  • Then − What should happen if the condition mentioned in WHEN is satisfied.
  • And/But – If we have several Given’s, When’s or Then’s, then we can use And /But.

Steps to create a Feature file

Step 1 – Create a new Maven project and add cucumber-java dependency to the POM.xml.

<dependency>
      <groupId>io.cucumber</groupId>
      <artifactId>cucumber-java</artifactId>
      <version>6.10.4</version>
</dependency>

Step 2 – It is suggested to create the Feature files in the src/test/resources source folder. By default, this folder is not present. So, first, create a Source Folder named src/test/resources. Right-Click on the project, and select New → Source Folder.

Provide the name to the Source Folder and click on the Finish button.

This creates a new Source Folder

Step 3 – We want all our Feature files to be present inside a folder. So, create a new folder with the name Features in the src/test/resources folder.

Right-Click on src/test/resources folder, and select New →Package. Provide name Features to the package and click the Finish button.

Step 4 – Create a Feature file in the Features package.

Right-Click on the Feature folder, select New ->File, and mention the name MyHoliday.feature. Click the Finish button. (Remember to add .feature at the end of the file, otherwise, this feature file will be just an ordinary plain text file).

The below image is an example of the new feature file created. This sample feature file gives an idea how an actual Feature file should look like.

Below is an example of a valid feature file.

Feature: Book flight ticket 

@BookOneWayFlight
Scenario: Book Flight for one way trip

Given I live in Dublin with 2adults and 2kids
And I want to book one way flight ticket from Dublin to London on 22nd   Jan 2020
When I search online
Then TripAdvisor should provide me options of flights on 22nd Jan 2020
And Cost of my flight should not be more than 50 Euro per person
And Tickets should be refundable

Congratulations. We are able to create a Feature file. Happy Learning!!

Cucumber Tutorial – How to setup Cucumber with Eclipse

HOME

In the previous tutorials, we discussed BDD (Behavior Driven Development) and GherkinCucumber 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, we will set up Cucumber with Eclipse. 

Prerequisites for Environment Setup for Cucumber

1. Download and Install Java

Java is a robust programming language. Java is a general-purpose programming language that is concurrent; class-based and object-oriented language. Java follows the concept of “write once and run anywhere (WORA) which means that compiled Java code can be run on all different platforms that support Java without the need for recompilation. Cucumber supports the Java platform for the execution. Click here to know How to install Java.

2. Download and Start Eclipse

Eclipse is an Integrated Development Environment (IDE). It contains a base workspace and an extensible plug-in system for customizing the environment. To download Eclipse, please refer to this tutorial – How to install Eclipse.

3. Maven –  How to install Maven on Windows 

Apache Maven is a software project management and comprehension tool. It uses the concept of a project object model (POM), Maven can manage a project’s build, reporting, and documentation from a central piece of information. MAVEN helps us in creating the project structure and managing and downloading the dependencies. We need to define the required dependencies in pom.xml. To install Maven on Windows, please refer to this tutorial – How to install Maven.

4. Install Cucumber Eclipse Plugin

The Cucumber plugin is an Eclipse plugin that allows the eclipse to understand the Gherkin syntax. Cucumber Eclipse Plugin highlights the keywords present in Feature File. To install Cucumber Eclipse Plugin, please refer to this tutorial – How to install Cucumber Eclipse Plugin

5. Configure Cucumber with Maven

Step 1 – Create a new Maven Project.

Click here to know the steps to create a new Maven project –  How to create a Maven project.

Step 2 – Open pom.xml of the project
         1. Go to package explorer on the left-hand side of Eclipse.
         2. Expand the project CucumberTest.
         3. Locate pom.xml file
         4. Add dependencies to POM.XML

Step 3 − Add dependency for selenium

This will indicate to Maven that Selenium jar files are to download from the central repository to the local repository.                                                                             

3.1 Open pom.xml is in the edit mode, create dependencies tag (), inside the project tag.                            3.2 Inside the dependencies tag, create a dependency tag ().

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.141.59</version>
</dependency>

Step 4 –  Add dependency for Cucumber-Java

This will indicate Maven, which Cucumber files are to be downloaded from the central repository to the local repository.  Create one more dependency tag.

<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>6.8.1</version>
</dependency>

Step 5 – Add dependency for Cucumber-JUnit

This will indicate Maven, which Cucumber JUnit files are to download from the central repository to the local repository. Create one more dependency tag. 

<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>6.8.1</version>
    <scope>test</scope>
</dependency>

Step 6 –  Add dependency for JUnit

This will indicate Maven, which JUnit files are to be downloaded from the central repository to the local repository. Create one more dependency tag.

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

Below is the screenshot which shows that Maven Project called CucumberDemo

This is the image of the pom.xml created

After adding the above mention dependencies, pom.xml looks like the image below

After adding the dependencies and then building the project, the below image shows the entire jar files added to the Maven Dependency.

Congratulations!! We are done with the setup of Cucumber in Eclipse. Happy Learning.

Cucumber – What is Gherkin

 

What is Gherkin?

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 will use English. Gherkin serves multiple purposes:-

  • Unambiguous executable specification
  • Automated testing using Cucumber
  • Document how the system actually behaves

Most lines in Gherkin document starts with one of the keywords. Comment lines are allowed anywhere in the file, start with a hash sign (#).

What is Feature File?

A file in which we store features, description about the features and scenarios to be tested.

Feature file consist of below-mentioned keywords:-

1) Feature – It is used provide high level description of test scenario and to group related scenarios

The first keyword in the Feature file is Feature keyword, followed by : and short text that describes the feature.

2) Scenario – It describes the steps followed to test the scenario and expected outcome of the scenario. 

3) Scenario Outline – It is used to run same scenario multiple times with different set of values.

4) Background – Suppose we find that Given steps are same for all Scenarios in a feature file. Then we should use Background. We can move these Given steps under Background section.

5) Steps – Each step starts with Given, When, Then, And or But. Cucumber executes each step in a scenario one at a time, in the sequence they have mentioned in the scenario. When Cucumber tries to execute a step, it looks for a matching step definition to execute.

  1. a) Given – It is used to describe the initial context of the scenario.  When a Given step is executed, it will configure the system to a well-defined state, such as creating & configuring objects or adding data to a test database.
  2. b) When – It is used to describe an event or action. This can be a person interacting with the system, or it can be an event triggered by another system.
  3. c) Then – It is used to describe the expected outcome of the scenario
  4. d) And/But – If we have several Given’s, When’s or Then’s, then we can use And /But.

Example of a Cucumber/BDD test:

Feature: Book flight ticket for one-way trip
Scenario:flight ticket for one-way trip from Dublin 

Given I live in Dublin 
And I want to book one way flight ticket from Dublin for 22nd Jan 20
When I search Online 
Then TripAdvisor should provide me options of flight for 22nd Jan 20 
And Cost of my flight should not be more than 50 
And Tickets should be refundable

What is Step Definition?

It is a Java method with an expression, which is used to link it to Gherkin steps. When Cucumber executes a Gherkin step, it will look for a matching step definition to execute.

Feature: Book flight ticket for one-way trip
Scenario: flight ticket for one-way trip from Dublin 
Given  I live in Dublin 
 
@Given ("^I live in Dublin$") 
public voidVacation()
          {
                   System.out.println("I live in Dublin");
          }

When Cucumber encounters a Gherkin step without a matching step definition, it will print a step definition snippet with a matching Cucumber Expression. We can use this as a starting point for a new step definition.

Scenario:flight ticket for one-way trip from Dublin 
Given  I live in Dublin

Here, Cucumber didn’t get step definition for the above-mentioned Given step. So, it will provide a snippet as mentioned below:-

@Given ("^I live in Dublin$")
public void i_live_in_Dublin() {
          // Write code here that turns the phrase above into concrete actions
 
    throw new cucumber.api.PendingException();
}

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

Introduction of Cucumber Testing Tool (BDD Tool)

 
 

In this tutorial, we will discuss about Cucumber Testing Tool. However, before starting with Cucumber, we should know what Behavior Driven Development (BDD) is.

What is Behavioral Driven Development (BDD)?

BDD is a set of practices that helps to reduce the rework caused by misunderstanding or vague requirements, narrow the communication gaps between development team, testing team and customers and promote continuous communication among them. In BDD, tests written in plain descriptive English (Gherkin) and they are more user focused. As the tests are in plain English, so everyone like Business stakeholders, Business Analyst, QA Team and Developers can contribute in testing. Cucumber is one such open source tool, which supports Behavior Driven Development (BDD). In simple words, Cucumber can defined as a testing framework, driven by plain English. It serves as documentation, automated tests, and a development aid – all in one.

How Cucumber works? 

  • Cucumber reads the code written in plain English text (Language Gherkin) in the feature file.
  • It finds the exact match of each step in the step definition.
  • The piece of code to execute can be different software frameworks like Selenium, Ruby on Rails, etc. 
  • This has become the reason for Cucumber’s popularity over other frameworks, like JBehave, JDave, Easyb, etc.

Cucumber supports over a dozen different software platforms like − 

  • Ruby on Rails 
  • Selenium 
  • PicoContainer 
  • Spring Framework 
  • Waitr

Advantages of Cucumber Over other Tools 

  • Cucumber supports different languages like Java.net and Ruby. 
  • It acts as a bridge between the business and technical language. We can accomplish this by creating a test case in plain English text. 
  • It allows the test script to written without knowledge of any code; it allows the involvement of non-programmers as well. 
  • It serves the purpose of end-to-end test framework unlike other tools. 
  • Due to simple test script architecture, Cucumber provides code re-usability.

Example of a Cucumber/BDD test: 

Feature: Book flight ticket for one-way trip
Scenario: Book flight ticket for one-way trip from Dublin to London 

Given I live in Dublin 
And I want to book one way flight ticket from Dublin to London for 23rd Oct 19
When I search Online 
Then TripAdvisor should provide me options of flight for 23rd Oct 19 
And Cost of my flight should not be more than 50 Euro per person 
And Tickets should be refundable

Any Business User or Stakeholder can understand above mentioned test case. They can provide their feedback, if this is expected from the functionality or not or do we need to add other steps too.