Hire QA – Specialized in QA Recruitment, Technical Interviews and Testing Solutions

Category: BDD Cucumber

Cucumber is a testing framework which supports Behavior Driven Development (BDD). It lets us define application behavior in plain meaningful English text using a simple grammar defined by a language called Gherkin. Cucumber itself is written in Ruby, but it can be used to “test” code written in Ruby or other languages including but not limited to Java, C# and Python.

Category: BDD Cucumber

TDD is an iterative development process. Each iteration starts with a set of tests written for a new piece of functionality. These tests are supposed to fail during the start of iteration as there will be no application code corresponding to the tests. In the next phase of the iteration, Application code is written with an intention to pass all the tests written earlier in the iteration. Once the application code is ready tests are run.

Category: BDD Cucumber
  • Unit test proves that the code actually works
  • Can drive the design of the program
  • Refactoring allows improving the design of the code
  • Low-Level regression test suite
  • Test first reduce the cost of the bugs
Category: BDD Cucumber

As Gherkin is a structured language it follows some syntax let us first see a simple scenario described in gherkin.

Feature: Search feature for users
This feature is very important because it will allow users to filter products

Scenario: When a user searches, without spelling mistake, for a product name present in inventory. All the products with similar name should be displayed

Given User is on the main page of www.myshopingsite.com
When User searches for laptops
Then search page should be updated with the lists of laptops

Category: BDD Cucumber
  • cobertura-2.1.1
  • cucumber-core-1.2.5
  • cucumber-java-1.2.5
  • cucumber-junit-1.2.5
  • cucumber-jvm-deps-1.0.5
  • cucumber-reporting-3.10.0
  • gherkin-2.12.2
  • junit-4.12
  • mockito-all-2.0.2-beta
Category: BDD Cucumber

This is a file where you will describe your tests in Descriptive language (Like English).
A feature file can contain a scenario or can contain many scenarios in a single feature file but it usually contains a list of scenarios.

Feature: Login Action

Scenario: Successful Login with Valid Credentials
Given User is on Home Page
When User Navigate to LogIn Page
And User enters UserName and Password
Then Message displayed Login Successfully

Scenario: Successful LogOut
When User LogOut from the Application
Then Message displayed LogOut Successfully

Category: BDD Cucumber
package cucumberTest;

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
                features = ""Feature""
                ,glue={""stepDefinition""}
                )

public class TestRunner {

}
Category: BDD Cucumber

Feature : Feature defines the logical test functionality you will test in this feature file.
Feature: LogIn Action Test

Or

Feature: LogIn Action Test
Description: This feature will test a LogIn and LogOut functionality

Or

Feature: LogIn Action Test
This feature will test a LogIn and LogOut functionality

Background : Background keyword is used to define steps that are common to all the tests in the feature file.
Scenario: Each Feature will contain a number of tests to test the feature. Each test is called a Scenario and is described using the Scenario: keyword.
Given : Given defines a precondition to the test.
When : When keyword defines the test action that will be executed.
Then : Then keyword defines the Outcome of previous steps.
And : And keyword is used to add conditions to your steps.
But : But keyword is used to add negative type comments.
* : This keyword is very special. This keyword defies the whole purpose of having Given, When, Then and all the other keywords. Basically Cucumber doesn’t care about what Keyword you use to define test steps, all it cares about what code it needs to execute for each step. That code is called a step definition
——————————————————–
Feature: LogIn Action Test
Description: This feature will test a LogIn and LogOut functionality

Scenario: Successful Login with Valid Credentials
* User is on Home Page
* User Navigate to LogIn Page
* User enters UserName and Password
* Message displayed Login Successfully

Category: BDD Cucumber

Step Definition is a java method in a class with an annotation above it.
An annotation followed by the pattern is used to link the Step Definition to all the matching Steps, and the code is what Cucumber will execute when it sees a Gherkin Step.
Cucumber finds the Step Definition file with the help of the Glue code in Cucumber Options.

Create a new Class file in the ‘stepDefinition‘ package and name it as ‘Test_Steps‘, by right click on the Package and select New > Class

@Given("^User is on Home Page$")
        public void user_is_on_Home_Page() throws Throwable {
                driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.store.demoqa.com");
                }
Category: BDD Cucumber

@CucumberOptions are like property files or settings for your test.

dryRun: true (checks if all steps have step definition)
features: set the path of feature files
glue: set the path of step definition files
tags: what tags in the feature files should be executed
monochrome: true (Display the console output in much readable way
format: what all report format to use
strict: true (will fail if there are undefined or pending steps)

Category: BDD Cucumber
package cucumberTest;

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
                features = ""Feature""
                ,glue={""stepDefinition""}
                ,dryRun=true
                ,monochrome = false
                ,format = {""pretty"", ""html:target/Destination""} )
                )

public class TestRunner {

}
Category: BDD Cucumber

Feature: Login Action

Scenario: Successful Login with Valid Credentials
Given User is on Home Page
When User Navigate to LogIn Page
And User enters “testuser_1” and “Test@123”

Then Message displayed Login Successfully

---------------------------------------------------------------------------
@When("^User enters \"(.*)\" and \"(.*)\"$")

public void user_enters_UserName_and_Password(String username, String password) throws Throwable {
driver.findElement(By.id("log")).sendKeys(username);
driver.findElement(By.id("pwd")).sendKeys(password);
driver.findElement(By.id("login")).click();
}
-----------------------------------------------------------------------------
@When(“^User enters \”([^\”]*)\” and \”([^\”]*)\”$”)
Category: BDD Cucumber
Feature: Login Action

Scenario: Successful Login with Valid Credentials
        Given User is on Home Page
        When User Navigate to LogIn Page
        And User enters ""testuser_1"" and ""Test@123""
        Then Message displayed Login Successfully

---------------------------------------------------------------------------
        @When(""^User enters \""(.*)\"" and \""(.*)\""$"")
        public void user_enters_UserName_and_Password(String username, String password) throws Throwable {
                driver.findElement(By.id(""log"")).sendKeys(username);          
            driver.findElement(By.id(""pwd"")).sendKeys(password);
            driver.findElement(By.id(""login"")).click();
        }
-----------------------------------------------------------------------------
@When(“^User enters \”([^\”]*)\” and \”([^\”]*)\”$”)
Category: BDD Cucumber

Scenario Outline:

This uses Example keyword to define the test data for the Scenario.
This works for the whole test.
Cucumber automatically run the complete test the number of times equal to the number of data in the Test Set.

Data Table:
No keyword is used to define the test data.
This works only for the single step, below which it is defined.
A separate code needs to understand the test data and then it can be run single or multiple times but again just for the single step, not for the complete test.

Category: BDD Cucumber
Scenario: Successful Login with Valid Credentials
 Given User is on Home Page
 When User Navigate to LogIn Page
 And User enters Credentials to LogIn
    | testuser_1 | Test@153 |
 Then Message displayed Login Successfully
--------------------------------------------------------------------------------
@And(""^User enters Credentials to LogIn$"")
        public void user_enters_testuser__and_Test(DataTable usercredentials) throws Throwable {

                //Write the code to handle Data Table
                List<List> data = usercredentials.raw();

                //This is to get the first data of the set (First Row + First Column)
                driver.findElement(By.id(""log"")).sendKeys(data.get(0).get(0)); 

                //This is to get the first data of the set (First Row + Second Column)
            driver.findElement(By.id(""pwd"")).sendKeys(data.get(0).get(1));

            driver.findElement(By.id(""login"")).click();
        }
Category: BDD Cucumber
Data Tables in Cucumber,  we pass Username & Password without Header, due to which the test was not much readable.

Scenario: Successful Login with Valid Credentials
        Given User is on Home Page
        When User Navigate to LogIn Page
        And User enters Credentials to LogIn
        | Username   | Password |
        | testuser_1 | Test@153 |
        Then Message displayed Login Successfully
----------------------------------------------------------------------------------
@When(""^User enters Credentials to LogIn$"")
        public void user_enters_testuser_and_Test(DataTable usercredentials) throws Throwable {

                //Write the code to handle Data Table
                List<Map> data = usercredentials.asMaps(String.class,String.class);
                driver.findElement(By.id(""log"")).sendKeys(data.get(0).get(""Username"")); 
                driver.findElement(By.id(""pwd"")).sendKeys(data.get(0).get(""Password""));
                driver.findElement(By.id(""login"")).click();
           }
=================================================================================
@When(""^User enters Credentials to LogIn$"")
        public void user_enters_testuser_and_Test(DataTable usercredentials) throws Throwable {

                //Write the code to handle Data Table
                for (Map data : usercredentials.asMaps(String.class, String.class)) {
                        driver.findElement(By.id(""log"")).sendKeys(data.get(""Username"")); 
                    driver.findElement(By.id(""pwd"")).sendKeys(data.get(""Password""));
                    driver.findElement(By.id(""login"")).click();
                        }

        }
Category: BDD Cucumber

We can define each scenario with a useful tag. Later, in the runner file, we can decide which specific tag (and so as the scenario(s)) we want Cucumber to execute. Tag starts with “@”. After “@” you can have any relevant text to define your tag like @SmokeTests just above the scenarios you like to mark. Then to target these tagged scenarios just specify the tags names in the CucumberOptions as tags = {“@SmokeTests”}.

@FunctionalTest
Feature: ECommerce Application

@SmokeTest @RegressionTest
Scenario: Successful Login
Given This is a blank test

@RegressionTest
Scenario: UnSuccessful Login
Given This is a blank test

package cucumberTest;

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
                features = ""Feature""
                ,glue={""stepDefinition""}
                ,dryRun=true
                ,monochrome = false
                ,format = {""pretty"", ""html:target/Destination""} )
                ,tags={""smokeTest""}
                )

public class TestRunner {

}
Execute all tests tagged as @SmokeTest OR @RegressionTest :	tags = {"SmokeTest,RegressionTest"}
Execute all tests tagged as @SmokeTest AND @RegressionTest :	tags = {"SmokeTest", "RegressionTest"}
Execute all tests of the feature tagged as @FunctionalTests but skip scenarios tagged as @SmokeTest :	tags = {"FunctionalTest","~SmokeTest"}
Category: BDD Cucumber

Cucumber supports hooks, which are blocks of code that run before or after each scenario. You can define them anywhere in your project or step definition layers, using the methods @Before and @After. Cucumber Hooks allows us to better manage the code workflow and helps us to reduce the code redundancy.

Category: BDD Cucumber

This prerequisite can be anything from:

Starting a webdriver
Setting up DB connections
Setting up test data
Setting up browser cookies
Navigating to certain page
or anything before the test
In the same way, there are always after steps as well of the tests like:

Killing the webdriver
Closing DB connections
Clearing the test data
Clearing browser cookies
Logging out from the application
Printing reports or logs
Taking screenshots on error
or anything after the test

Category: BDD Cucumber
package utilities;
import cucumber.api.java.After;
import cucumber.api.java.Before;

public class Hooks {
	
	@Before
    public void beforeScenario(){
        System.out.println(""This will run before the Scenario"");
    }	
	
	@After
    public void afterScenario(){
        System.out.println(""This will run after the Scenario"");
    }
}
Category: BDD Cucumber

Feature: Test Tagged Hooks

@First
Scenario: This is First Scenario
Given this is the first step
When this is the second step
Then this is the third step

@Second
Scenario: This is Second Scenario
Given this is the first step
When this is the second step
Then this is the third step

@Third
Scenario: This is Third Scenario
Given this is the first step
When this is the second step
Then this is the third step

"package utilities;

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

public class Hooks {

	@Before
    public void beforeScenario(){
        System.out.println(""This will run before the every Scenario"");
    }

	@After
    public void afterScenario(){
        System.out.println(""This will run after the every Scenario"");
    }

	@Before(""@First"")
    public void beforeFirst(){
        System.out.println(""This will run only before the First Scenario"");
    }	

	@Before(""@Second"")
    public void beforeSecond(){
        System.out.println(""This will run only before the Second Scenario"");
    }	

	@Before(""@Third"")
    public void beforeThird(){
        System.out.println(""This will run only before the Third Scenario"");
    }

	@After(""@First"")
    public void afterFirst(){
        System.out.println(""This will run only after the First Scenario"");   
    }	

	@After(""@Second"")
    public void afterSecond(){
        System.out.println(""This will run only after the Second Scenario"");   
    }	

	@After(""@Third"")
    public void afterThird(){
        System.out.println(""This will run only after the Third Scenario"");   
    }	
}"
Category: BDD Cucumber

@Before(order = int) : This runs in increment order, means value 0 would run first and 1 would be after 0.
@After(order = int) : This runs in decrements order, means apposite of @Before. Value 1 would run first and 0 would be after 1.

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Before;
public class PriorityTest {

@Given ("^User navigates to Reorder page$")
public void navigate_reorder () {
      System.out.println ("Reorder page is navigated");
    }
@Before (order = 2)
    public void precondition1 () {
        System.out.println ("The precondition1 is to be executed");
    } 
@Before (order = 1)
    public void precondition2 () {
        System.out.println ("The precondition2 is to be executed");
    } 
}
Category: BDD Cucumber

Background in Cucumber is used to define a step or series of steps that are common to all the tests in the feature file.
A Background is much like a scenario containing a number of steps. But it runs before each and every scenario were for a feature in which it is defined.

Feature: Test Background Feature
Description: The purpose of this feature is to test the Background keyword

Background: User is Logged In
Given I navigate to the login page
When I submit username and password
Then I should be logged in


Scenario: Search a product and add the first product to the User basket
Given User search for Lenovo Laptop
When Add the first laptop that appears in the search result to the basket
Then User basket should display with added item

Scenario: Navigate to a product and add the same to the User basket
Given User navigate for Lenovo Laptop
When Add the laptop to the basket
Then User basket should display with added item

Category: BDD Cucumber

Profile in cucumber allows a way to define a group of tests in a feature file to run a selected group instead of executing all the commands while testing a feature. Cucumber profiles allow running step definitions and features.

Use the command below to run the cucumber profile. 

Cucumber features -p
Category: BDD Cucumber

We can add comments in the Cucumber code. The comments are incorporated in code mostly for documentation and not for including program logic. It makes the code easier to apprehend and to debug the errors. Also, comments can be put at any point in the code.

Inside the feature file, the comments are added after the (#) symbol and the step definition contains comments after the (//) symbol.

Feature file with comments.

  • Feature: Customer verification
  • # Scenario with customer
  • Scenario: Verify customer details
  • Given User navigates to Customer Information Page
import cucumber.api.java.en.Given;
public class CustomerInformation {
 
@Given ("^User navigates to Customer Information Page$")
//method to map @Given scenario in feature file
public void navigate_to_customerInformation () {
      System.out.println ("Customer Information Page is navigated");
    }
}
Category: BDD Cucumber

We can use regular expressions in the Cucumber framework inside the step definition file. The regular expression can be used to combine two or more similar steps in the feature file within a test method in the step definition file. Also, the regular expression is used for data parameterization in Cucumber as the Feature New User Registration in the feature file described previously.

Feature file implementation.

  • Feature: Student Study Schedule
  • Description: Verify student study schedule
  • Scenario: Verify hours spent on science subjects
  • Given Student studies Chemistry on Tuesday
  • Given Student studies Mathematics on Tuesday
  • Given Student has thirty minutes recess
import cucumber.api.java.en.Given;
public class StudentSchedule {
 
@Given ("^Student studies ([^\"]*) on Tuesday$")
public void student_Tuesday_schedule (String subject) {
       if (subject.equals ("Chemistry")){
              System.out.println ("Student studies Chemistry on Tuesday");
        } else {
               System.out.println ("Student studies Mathematics on Tuesday");
         }
    }
@Given ("^Student has thirty minutes recess$")
public void student_recess () {
      System.out.println ("Student recess time is thirty minutes");
    }
}
Category: BDD Cucumber

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

@CucumberOptions(
	features = "src/test/resources/functionalTests",
	glue= {"stepDefinitions"},
	plugin = { "pretty", "html:target/cucumber-reports" },
	monochrome = true
)
Category: BDD Cucumber

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

@CucumberOptions(
	features = "src/test/resources/functionalTests",
	glue= {"stepDefinitions"},
	plugin = { "pretty", "json:target/cucumber-reports/Cucumber.json" },
	monochrome = true
)
Category: BDD Cucumber

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

@CucumberOptions(
	features = "src/test/resources/functionalTests",
	glue= {"stepDefinitions"},
	plugin = { "pretty", "junit:target/cucumber-reports/Cucumber.xml" },
	monochrome = true
)