Cucumber BDD with Selenium

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

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

Behavior Driven Development is an extension of Test-Driven Development, and it is used to test the system rather than testing a 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 a 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.

Parameterize Cucumber BDD with selenium

Gherkin Language with Cucumber

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 set up your environment, use the system, and verify the result.

The purpose of Gherkin is to be able to express examples that describe the 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 start 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 :

The 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 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.
  • The 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

Tags & Hooks in Cucumber with Selenium

Cucumber Installation in Selenium

For installing cucumber, we need to 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 the jar file option on the search result.
    • cucumber-core
    • cucumber-html
    • cucumber-java
    • cucumber-junit
    • cucumber-jvm-deps
    • 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

  1. Accept the plugin to restart the eclipse. drgged-cucumber-jvm-eclipse-plugin-selenium-webdriver

TestNG unit Testing Framework in Selenium

Feature file in Cucumber

We have to write all the Feature files under a separate folder so that it would be easy to manage.
Similarly, we also have to write the step definition files in a separate folder.

Feature: Sample test
  Search Chercher Tech in Google 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. 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 a test step but not a verification, mostly used for navigation purpose

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

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

    7. Background: Background in Cucumber is used to define a step or series of steps that are common to all the tests in the feature file. Background steps will be executed for all the scenarios present in the Gherkin feature file

    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 contain all our feature files of our project.

    Place the above Feature code in Sample.feature file.

Page Object Model in Selenium

JUnit Test Runner in Cucumber

We can write an n-number of scenarios and test steps and steps definitions using cucumber, but cucumber does 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 literally.

The execution point of the cucumber test scenarios depends on the framework that you are using for executing the tests that 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 the 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 the Feature file location and the steps related to those Feature file with CucumberOptionsannotation 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, do not worry about missing steps

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

iFrames / Frames in Selenium

Step Definition File

Features files contain one or more scenarios per feature file. Every scenario can contain n-number of test steps using the Gherkin keywords

For each and every step we have to provide the implementations, I am telling you again, just because you wrote steps in Gherkin language does not mean the 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 the Test Runner class without test steps, TestRunner gives an error to implement the test steps, so we copy the same steps and can create a steps definition 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 progsdriverserverchromedriver.exe");
		driver = new ChromeDriver();
		driver.get("https://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");
	}
}

Strings in Java & Selenium

Background in 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. Background steps will be executed for all the scenarios present in the Gherkin feature file

You might have steps like navigating to your application and opening a specific page such kind of things will come in Background.

The background is also similar to scenarios; the background contains multiple steps.

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

	Background: User is Logged In
		Given Open Chrome browser
		Then Navigate to Google Page

	Scenario: Search Google for Chercher Tech
	  Given search for chercher tech

	Scenario: Search Bing for Chercher Tech
	  Given search for selenium cherchertech

	Scenario: Search DuckDuckGo for Chercher Tech
	  Given search for protractor chercher tech

Step definition file

public class Steps_Sample {
	WebDriver driver;

	@Given("^Open Chrome browser$")
	public void open_Chrome_browser() throws Throwable {
		System.setProperty("webdriver.chrome.driver", "D:Eclipse progsdriverserverchromedriver.exe");
		driver = new ChromeDriver();
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	@Then("^Navigate to Google Page$")
	public void navigate_to_Google_Page() throws Throwable {
		driver.get("https://google.com");
	}

	@Given("^search for chercher tech$")
	public void search_for_chercher_tech() throws Throwable {
		driver.findElement(By.name("q")).sendKeys("chercher tech");
	}

	@Given("^search for selenium cherchertech$")
	public void search_for_selenium_cherchertech() throws Throwable {
		driver.findElement(By.name("q")).sendKeys("selenium cherchertech");
	}

	@Given("^search for protractor chercher tech$")
	public void search_for_protractor_chercher_tech() throws Throwable {
		driver.findElement(By.name("q")).sendKeys("protractor chercher tech");
	}
}

Inheritance in OOPS | Selenium

About Author :

I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions