Cucumber Tutorial for Beginners:Part 2

Cucumber Tutorial for Beginners:Part 2

2019 / 9 / 6

Cucumber, Selenium, Data Driven Testing, Eclipse

In the last blog post we have discussed installation of all the software required to get started with Cucumber test.

This blog post will be focussed on writing cucumber test script, but before jumping straight to test script we will first write a Selenium Test Script and finally we will convert Selenium Test to Cucumber Feature File.

I hope you have followed the complete tutorial and I expect by now you have completed the following steps that are prerequisites for writing a Cucumber Selenium Test:

  1. Download & Install Java

  2. Download and Install Eclipse

  3. Install Cucumber Eclipse Plug-in

  4. Download Cucumber

  5. Download Selenium WebDriver Client

  6. Configure Eclipse with Selenium & Cucumber

Steps to create Folder Structure:

  1. Create a new package by Right click on src folder-> New-> Package

Package

  1. Name it as “cucumberTestScript” and click on Finish button.

TestScript

  1. Create another folder by Right click on src folder-> New->Package and name it step Definition and click on Finish button.

3

4

  1. Now create a new folder by Right click on project “Online Shopping”->New->Folder

5

  1. Name it as “Feature” and click on Finish button.

6

Steps to write a Selenium Java Test:

We will write a simple Selenium Test Script for Login functionality and then convert that script to Cucumber script.

  1. Create a new class file in cucumberTestScript package and name it as SeleniumTestScript by right click on Package-> New-> Class. Select the option “public static void main” and click on Finish button.

7

8

  1. Now we will write a script that will perform following steps in Selenium:
  1. Launch the Browser
  2. Navigate to Home Page
  3. Click on the LogIn link
  4. Enter UserName and Password
  5. Click on Submit button
  6. Print a successful LogIn message
  7. LogOut from the application
  8. Print a successful LogOut message
  9. Close the Browser

Code:

**package** cucumberTestScript;
**import** java.util.concurrent.TimeUnit;
**import** org.openqa.selenium.By;
**import** org.openqa.selenium.WebDriver;
**import** org.openqa.selenium.firefox.FirefoxDriver;
**public** **class** SeleniumTestScript {
**private** **static** WebDriver _driver_ = **null**;
**public** **static** **void** main(String[] args) {
    _driver_ = **new** FirefoxDriver();// Create a New Chrome Driver
    _driver_.manage().timeouts().implicitlyWait(10, TimeUnit.**_SECONDS_**);//Implicit wait means wait for mentioned number of seconds for a response before throwing exceptions.
    _driver_.get("http://www.store.demoqa.com");// Launch the Online Store Website.
    _driver_.findElement(By._xpath_(".//*[@id='account']/a")).click();//Find element with ID "account"
    _driver_.findElement(By._id_("log")).sendKeys("testuser_1");// Find element with ID log and Enter Username in the element with ID "log"
    _driver_.findElement(By._id_("pwd")).sendKeys("[email protected]");// Find element with ID pwd and Enter Password in the element with ID "pwd"
    _driver_.findElement(By._id_("login")).click();//Submit the form.
    System.**_out_**.println("Login Successfully");// Print successful logIN Message.
    _driver_.findElement (By._xpath_(".//*[@id='account_logout']/a")).click();// FInd element with ID Attribute "account_logout""
    System.**_out_**.println("LogOut Successfully");//Print successful LogOut Message.
    _driver_.quit();//Close the driver.
    }
}

Right Click on the Eclipse code->Run As->Java Application.

After few seconds Chrome browser will open and you will see with the help of the script,Selenium will launch Online Store demo application and perform sign in.

Feature File

Feature file is an entry point to the cucumber tests. In this file we will describe test in descriptive language like English. It is an essential part of Cucumber as it serves as an automation script as well as a live Document.

Feature file can contain a scenario or many scenarios but usually it contains a list of scenarios.

Let’s get started with a Feature File.

  1. Right click on Feature Folder-> New-> File.

9

  1. Name it “LogInTest.feature” and click on Finish button.“.feature” extension is important as it will help feature file to automatically detect the stories.

10

11

  1. We will write the first Cucumber Test Script

    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
    

Don’t worry about the syntax and how to write a Cucumber Test Script, we will learn to write a Test Script later in this article. Till then just have a look and get a basic understanding of intent of the test.

Keywords:

You must have noticed from the above screenshot, that there are some highlighted words in the file. These are the Keywords from Gherkin language. This language we use basically for writing test script in Cucumber feature file. There are many more keywords in Gherkin. We will discuss later in the article. For the time being we will focus on the following 4 keywords:

  1. Feature: This keyword gives the definition of feature you will be testing in the test below.
  2. Given: Tells the pre-condition of the test to be executed.
  3. And: Defines additional conditions of the test to be executed.
  4. Then: States the post condition of the test to be executed. You can also say that it is an expected result of the test.

Gherkin

Now let’s get back to Gherkin. It implements the principle of Business readable domain specific language(BRDSL). Domain specific language gives you the ability to describe your application behaviour.

Steps to install Natural Eclipse Editor for Gherkin:

You will get this option automatically when you create a file with .feature extension. Otherwise, you can anytime go to Eclipse Marketplace and look for the same to install it.

  1. Go to Help-> Eclipse Marketplace.

12

  1. Type “Natural” in the search bar.

13

  1. Select “Natural 0.7.6” option.
  2. Click on Install.
  3. This will give your another option- You would like to use it for Cucumber or JBehave Editior.Select Cucumber option and click on Confirm.

14

  1. Last step is to accept the Terms and Conditions.

15

  1. Once done, you will be asked to restart Eclipse.

Cucumber uses Junit framework to run tests. Since cucumber uses Junit, we need to have a Test Runner class. This class uses the annotation @RunWith(), It is like a starting point for Junit to start executing test.

  1. Right click on the package “cucumberTestScript”->New->Class.

16

  1. Name it “TestRunner” and click the Finish button.

TestRunner Class

package cucumberTestScript;
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 {
}

For the curious minds, we will discuss the code.

  1. import.org.junit.runner.RunWIth will import @RunWith annotation from Junit class. It tells Junit that test should start running using Cucumber class present in “Cucumber.api.junit” package.
  2. import.cucumber.api.junit.CucumberOptions imports @CucumberOptions annotation.This annotation tells Cucumber where to find feature file, what reporting system to use and many other things.

Now it;s finally time to run the Cucumber Test

Click on the TestRunner class and click Run As->JUnit Test Application.

You must be wondering where is the java code that will execute for these tests? You need to wait for another 5 minutes as I will be discussing the Java code in a short moment. First observe the output on the console window that appears after running the code that we have created till now.

Our next target is to execute feature file. In order to test feature file, we need to write step definition for each step in the feature file.

When Cucumber executes a step in a Scenario it will look for a matching Step Definition to execute.

Step Definition is basically a java method in a class with an annotation above it.

  1. Create a new Class file in the “stepDefinition” package and name it as “TestSteps” by right click on the package-> New->Class. Do not select the public static void main option and click on Finish button.
  2. Take a look at the message displayed in the console. Copy paste the text inside the red rectangle inside the TestSteps class created.

package stepDefinition;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
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 Test_Steps {
      public static WebDriver driver;
      @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("http://www.store.demoqa.com");
      }
      @When("^User Navigate to LogIn Page$")
      public void user_Navigate_to_LogIn_Page() throws Throwable {
            driver.findElement(By.xpath(".//*[@id='account']/a")).click();
      }
      @When("^User enters UserName and Password$")
      public void user_enters_UserName_and_Password() throws Throwable {
            driver.findElement(By.id("log")).sendKeys("testuser_1");
            driver.findElement(By.id("pwd")).sendKeys("[email protected]");
            driver.findElement(By.id("login")).click();
      }
      @Then("^Message displayed Login Successfully$")
      public void message_displayed_Login_Successfully() throws Throwable {
            System.out.println("Login Successfully");
      }
      @When("^User LogOut from the Application$")
      public void user_LogOut_from_the_Application() throws Throwable {
            driver.findElement (By.xpath(".//*[@id='account_logout']/a")).click();
      }
      @Then("^Message displayed Logout Successfully$")
      public void message_displayed_Logout_Successfully() throws Throwable {
            System.out.println("LogOut Successfully");
      }
}
  1. Now right click on the TestRunner class-> Run As->JUnit Test

You will see that Cucumber successfully launches browser and logout successfully.

Cucumber starts with reading the feature file. The moment it encounters the first annotation @Given, it will find the matching method in the stepDefinition file and executes the code written inside the function.

You might also like