What is Cucumber BDD

Cucumber is a tool based on Behavior Driven Development framework which is used to write user acceptance tests for web applications

It allows automation of functional validation in easily readable and understandable format (like plain English) to Business Analysts, Developers, Testers, etc.

Behavior Driven Development is extension of Test Driven Development and it is used to test the system rather than testing the particular piece of code.

Cucumber can be used along with Selenium, Watir, and Capybara etc.

Cucumber is a Java framework for BDD, by its support for the particular set of interactions between team members and stakeholders.

Cucumber can execute plain-text functional (feature) specifications as automated tests. The language that Cucumber understands is called Gherkin.

Cucumber supports writing specifications in about 30 spoken languages, making it easy to deliver better for teams outside of English-speaking territories or those working on internationally targeted software.

Gherkin Language

The purpose of the Cucumber test framework is to execute examples expressed in Gherkin.

Gherkin is the high level language where you express examples in plain language using Given/When/Then to setup your environment, use the system, and verify the result.

The purpose with Gherkin is to be able to express examples that describe a behavior of a system in such a way that anyone with domain knowledge can understand what works and how it is supposed to work.

Gherkin language file starts with the feature you want to test, and then the scenarios for the feature to be tested.

A feature file can contain one feature and one or more scenarios for the features, a scenario can contain n number of steps

features :

Every *.feature file conventionally consists of a single feature. Lines starting with the keyword Feature: (or its localized equivalent) followed by three indented lines starts a feature.

A feature usually contains a list of scenarios. You can write based on your need until the first scenario, which starts with Scenario:

scenarios :

Scenario is one of the core Gherkin structures. Every scenario starts with the Scenario: keyword, followed by an optional scenario heading.

A feature can have one or more scenarios, and every scenario consists of one or more steps.

steps :

Each line in a scenarios is considered as a step.

Steps are formed using Given, When, Then, And gherkin keywords, all the keywords start with Uppercase

Make sure Keywords and colon (:) should not have any space in between them.

Step should be clear and it should not create any confusion for the reader.

We should Develop a test step in a way that, it can be used within multiple scenarios and scenario outlines.


									Feature: Serve coffee
									  Coffee should not be served until paid for
									  Coffee should not be served until the button has been pressed
									  If there is no coffee left then money should be refunded

									Scenario: Buy last coffee
									  Given there are 1 coffees left in the machine
									  And I have deposited 1$
									  When I press the coffee button
									  Then I should be served a coffee			
									

Cucumber Installation in Selenium

For installing cucumber, we need add below jar files into eclipse using Add External Jars

1. Navigate to https://mvnrepository.com
2. Search and download below jar files by clicking jar file option on the search result.
i. cucumber-core
ii. cucumber-html
iii. cucumber-java
iv. cucumber-junit
v. cucumber-jvm-deps
vi. gherkin
3. Navigate to https://marketplace.eclipse.org/content/cucumber-jvm-eclipse-plugin
4. Click and drag the install button into somewhere in Eclipse.
drag-cucumber-jvm-eclipse-selenium

5. Accept the plugin to retstart the eclipse.
drgged-cucumber-jvm-eclipse-plugin-selenium-webdriver

Feature file in Cucumber

We have to write all the Feature files under separate folder, so that it would be easy to manage.

Similarly we also have to write the step definition files in separate folder.


									Feature: Sample test
									  Search Chercher Tech in Goole and click first result
									  

									Scenario: Search Google for Chercher Tech
									  Given There is opened Chrome browser 
									  When I searched Chercher Tech in searchbar
									  And When I press Enter key
									  Then I should see Chercher Tech results
									  Then I click on the First result to see the Home page
									  
									

Components of Feature file :


1. Feature: What is you are going to test, or your user story description.

2. Scenario: What is the functionality of the Feature you are going to test

3. Given: it is pre-condition, what should be there

4. When: When is used for performing an test step but not a verification, mostly used for navigation purpose

5. Then: Mostly this contains the expectation or an assertion for the check point

6. And: It is nothing but continuation of above steps (could be either When, Then)

For Our project purpose, we would be creating a package called features outside the src package.

Create a file called Sample.feature under the features package, this package will contains all our feature files of our project.

Place the above Feature code in Sample.feature file.
sample-feature-bdd-cucumber

Test Runner

We can write n-number of scenarios and test steps and stps definitions using cucumber, but cucumber doenot not implicitly run your test scenarios

We have to provide what we want to execute in cucumber, Test Runner class helps us to run the cucumber scenarios. This is the starting point of the Execution of Cucumber, but not litrally.

The execution point of the cucumber test scenarios depends on the framework that you are using for executg the tests it could be either JUnit or TestNG.

I hope you are aware that the starting point of the JUNit is the main method present in the JUnit.class

Similar to JUnit, if you are using TestNg along with cucumber then your starting point would be main method present in the TestNG.class

As of now I would go with JUnit Runner :
We have to import the Runner class from the JUnit and also we have to provide where the feature files are present.

We have to pass Feature file location and the steps related to those Feature file with CucumberOptions annotation or decorator


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

									@RunWith(Cucumber.class)
									@CucumberOptions(features= "features", glue= {"testDefinitions"})
									public class TestRunner {

									}			
									

Run the above code with Run AS > JUnit, donot worry about missing steps

Once the executon is over you will find the output as You can implement missing steps with the snippets below, Now copy paste these stps into your Stepdefinition class (below one)

Step Definition File

Features files contains one or more scenarios per feature file.

Every scenario can contain n-number of test steps using the the Gherkin keywords

For each and every step we have to provide the implementations, I am telling you agin, just because you wrote steps in Gherkin language doenot mean computer will understand perform the tasks that you said in Gherkin language.

Every step should have implementations, this implementation is nothing but the methods in java but decorated with the test step detail.

Create a package under the src folder called stepDefinitions, this package will have all the step definition code files.

Create a java class called Steps_Sample inside the stepDefinitions folder.

steps-sample-bdd-cucumber

In this Steps_Sample class only you have to paste the steps copied from the above execution

Change the steps content like below (Non-Selenium Version):


package testDefinitions;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class Steps_Sample {
	@Given("^There is opened Chrome browser$")
	public void there_is_opened_Chrome_browser() throws Throwable {
		System.out.println("Opening Chrome");
	}
	@When("^I searched Chercher Tech in searchbar$")
	public void i_searched_Chercher_Tech_in_searchbar() throws Throwable {
		System.out.println("Searching the text on search bar");
	}
	@When("^When I press Enter key$")
	public void when_I_press_Enter_key() throws Throwable {
		System.out.println("Press Enter key");
	}
	@Then("^I should see Chercher Tech results$")
	public void i_should_see_Chercher_Tech_results() throws Throwable {
		System.out.println("User should see results relate to CherCher Tech");
	}
	@Then("^I click on the First result to see the Home page$")
	public void i_click_on_the_First_result_to_see_the_Home_page() throws Throwable {
		System.out.println("User should able to click first link");
	}
}			

Now run the above code as Junit Tests from the TestRunner class.

result-cucumber-bdd-selenium

When you ran with Test Runner class without test steps, TestRunner gives error to implement the test steps, so we copy same steps and can create a steps defintion class.

In steps, You can see @When, @Given, @Then, kind of decorators (annotations). These annotations will map the Feature file steps with steps present in stepDefinition methods. I hope you understood the relation between the feature steps and StepDefinitions, Now lets re-write the above program to selenium code.


package testDefinitions;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class Steps_Sample {
	WebDriver driver;
	@Given("^There is opened Chrome browser$")
	public void there_is_opened_Chrome_browser() throws Throwable {
		System.setProperty("webdriver.chrome.driver", "D:\\Eclipse progs\\driverserver\\chromedriver.exe");
		driver = new ChromeDriver();
		driver.get("http://google.com");
		System.out.println("Opening Chrome");
	}
	@When("^I searched Chercher Tech in searchbar$")
	public void i_searched_Chercher_Tech_in_searchbar() throws Throwable {
		driver.findElement(By.name("q")).sendKeys("CherCher Tech");
		System.out.println("Searching the text on search bar");
	}
	@When("^When I press Enter key$")
	public void when_I_press_Enter_key() throws Throwable {
		driver.findElement(By.name("q")).sendKeys(Keys.ENTER);
		System.out.println("Press Enter key");
	}
	@Then("^I should see Chercher Tech results$")
	public void i_should_see_Chercher_Tech_results() throws Throwable {
		driver.findElement(By.partialLinkText("CherCher"));
		System.out.println("User should see results relate to CherCher Tech");
	}
	@Then("^I click on the First result to see the Home page$")
	public void i_click_on_the_First_result_to_see_the_Home_page() throws Throwable {
		driver.findElement(By.partialLinkText("CherCher")).click();
		System.out.println("User should able to click first link");
	}
}

			

Parameterize Cucumber BDD

Parametterizng is nothing but useing the custom values or using values without hard coding the values.

In above example we have seen everything as hard coded, from google to search term, but our requirements may change and we should be in a position to change the values without touching the step definitions.

Real Time Scenario : Product Owner (BA) gives you a requirement saying that all the links present in the webpage should have a color code of #0000ff (Blue).

Based on the given requirement you have automated the scenario condition and you took a long sick leave because of your appraisal review ( just kidding )

Now Prduct owner realizes that she has to change the color code to #000080 (navy Blue), but as a intelligent person you have hard coded the #0000ff in step definition.

As Long as I am familiar with, Product Owners are not familiar with programming and because which only they wanted the cucumber, In that also you have hard coded the values, so because of this she cannot change the value in the feature file, if she changes something tests will fails the the step definitions are not available for the changed step.

But if you can provide the Product owner the ability to change the values on need basis and if your step defoinition can work based on the chnage of value , would not it be great ?

So enable the parameterization in cucumber we have to provide the values in ""(double quotes) which we want to parameterize.

Lets' re-write the above example in the paramererize way, Before that when we parameterize the step then we have to receive those parameter values in your step definition to use it for further.

As you know, Cucumber works or invokes the step definition method using regular expression but we are not that much sure that we can write the regular expression, so instead of writng a regular expression, run the TestRunner file and in output cucumbr suggest as that there is some step missing.

suggested-parameter-cucumber-bdd-selenium

We have to take that regular expression(I have highlighted in above image) use it along with out step definition.


Feature: Sample test
  Search Chercher Tech in Goole and click first result

Scenario: Search Google for Chercher Tech
  Given There is opened "Chrome browser" 
  When I searched "Chercher Tech" in searchbar
  And When I press Enter key
  Then I should see Chercher Tech results
  Then I click on the First result to see the Home page			

Change the step definiton steps like below one based on the regular expression copied, keep remaining methods same as previous code.


public class Steps_Sample {
	WebDriver driver;
	@Given("^There is opened \"([^\"]*)\"$")
	public void there_is_opened_Chrome_browser(String browser) throws Throwable {
		if(browser.equals("chrome"))
		{
			System.setProperty("webdriver.chrome.driver", "D:\\Eclipse progs\\driverserver\\chromedriver.exe");
			driver = new ChromeDriver();
		}else if(browser.equals("firefox")) {
			System.setProperty("webdriver.firefox.driver", "D:\\Eclipse progs\\driverserver\\geckodriver.exe");
			driver = new FirefoxDriver();
		}
		
		driver.get("http://google.com");
		System.out.println("Opening "+browser);
	}
	@When("^I searched \"([^\"]*)\" in searchbar$")
	public void i_searched_Chercher_Tech_in_searchbar(String searchTerm) throws Throwable {
		driver.findElement(By.name("q")).sendKeys(searchTerm);
		System.out.println("Searching the text on search bar");
	}			

Also change the Feature file according the parameter you accept.

Data from Exampes in Cucumber BDD

In above exampe we have seen to read the data from the user input but if uoser wants to test the same scenario with more than one data, then we should use a concept called Data table in Cucumber or it is also called as Examples in Cucumber BDD.

Data table in cucumber should be formed using Pipe ( | )symbol, and every new line will be considered as new data. examples-data-table-cucumber-bdd-selenium

We can have n-number of tables and n-number of columns in teh data table in cuccumber BDD

The parameters which you want to read from the data table must be mentioned inside the < >

parmeter name inside teh angular brace should match woth the column name in the Examples we provided.

Normally people will write the Examples at the end of the every scenario if required

To use an example we need to change the Scenario: tag into Scenario Outline:, otherwise cucumber bdd throws error on compilation.

Lets rewrite the above scenario to read the data from the Examples.


Feature: Sample test
  Search Chercher Tech in Google and click first result

  Scenario Outline: Search Google for Chercher Tech
    Given There is opened "<browser>"
    When I searched "<searchterm>" in searchbar
    And When I press Enter key
    Then I should see results
    Then I click on the First result to see the Home page

    Examples: 
      | browser | searchterm        |
      | firefox | chercher tech     |
      | chrome  | selenium chercher |
			

The step definition file is below, and there is no change in TestRunner class


package testDefinitions;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class Steps_Sample {
	WebDriver driver;
	@Given("^There is opened \"([^\"]*)\"$")
	public void there_is_opened_Chrome_browser(String browser) throws Throwable {
		if(browser.equals("chrome"))
		{
			System.setProperty("webdriver.chrome.driver", "D:\\Eclipse progs\\driverserver\\chromedriver.exe");
			driver = new ChromeDriver();
		}else if(browser.equals("firefox")) {
			System.setProperty("webdriver.gecko.driver", "D:\\Eclipse progs\\driverserver\\geckodriver.exe");
			driver = new FirefoxDriver();
		}
		
		driver.get("http://google.com");
		System.out.println("Opening "+browser);
	}
	@When("^I searched \"([^\"]*)\" in searchbar$")
	public void i_searched_Chercher_Tech_in_searchbar(String searchTerm) throws Throwable {
		driver.findElement(By.name("q")).sendKeys(searchTerm);
		System.out.println("Searching the text on search bar");
	}
	@When("^When I press Enter key$")
	public void when_I_press_Enter_key() throws Throwable {
		driver.findElement(By.name("q")).sendKeys(Keys.ENTER);
		System.out.println("Press Enter key");
	}
	@Then("^I should see results$")
	public void i_should_see_Chercher_Tech_results() throws Throwable {
		driver.findElement(By.partialLinkText("CherCher"));
		System.out.println("User should see results relate to CherCher Tech");
	}
	@Then("^I click on the First result to see the Home page$")
	public void i_click_on_the_First_result_to_see_the_Home_page() throws Throwable {
		driver.findElement(By.partialLinkText("CherCher")).click();
		System.out.println("User should able to click first link");
	}
}
			
data-table-cucumber-bdd-selenium

Data table as Map :

 
Join My Facebook Group
Join Group
 

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
Copyright © CherCher Tech