{{announcement.body}}
{{announcement.title}}

Business Driven Development by Selenium Testing With Gherkin

DZone 's Guide to

Business Driven Development by Selenium Testing With Gherkin

In this article, I’ll further explore this topic on how to do Business-Driven Development by Selenium testing with Gherkin.

· Web Dev Zone ·
Free Resource

Cucumber and Selenium are widely used frameworks for BDD (Behaviour Driven Development) and browser automation respectively. Although on paper, it seems like a nice pair, when it comes to reality, a lot of testers shy away from it.  The major reason behind this is Gherkin, as most testers hesitate to use it, as it feels like an additional task since the test scripts are still to be written separately. 

But this is not true for all. Using Gherkin can actually help in testing as it serves as a good document for all the features and can be written by anyone even with almost zero coding knowledge. 

Being written in Gherkin, it acts as a bridge between various layers, PMs --> Dev --> Testers --> Clients. Let us move towards understanding BDD with Gherkin and how it can make Selenium testing better.

In this article, I’ll further explore this topic on how to do Business-Driven Development by Selenium testing with Gherkin. Before I start with Gherkin, I’d like to give you a small brief about BDD (Behaviour Driven Development, not to be confused with Business-Driven Development.

What Is BDD?

Behavior Driven Development, popularly known as BDD, is a widely used development approach in the software industry. It empowers its user to write cases in plain English language. This helps team members even with no technical know-how to understand what is going on in the project that closes the gap between business people and technical people. 

In addition to a low technicality and easier-to-understand approach, the main advantage of BDD is that it transpires from TDD ie. Test-Driven Development, which supports automated testing with multiple test data with minimum intervention in code. 

Cucumber – A BDD Framework Tool: BDD is implemented with the help of the Cucumber framework, which helps in automating the cases in a well-formatted and readable form. 

Cucumber feature files: These files, written, in Gherkin language, ending with the .feature extension, are an integral part of Cucumber and are used for application specifications.

Getting Started With Gherkin for Selenium Testing

Gherkin for Selenium Testing is a Business Readable, Domain Specific Language which entitles its users to write effective tests in a well-documented way that requires the least reasoning and involved logic details.

Let us understand this with a Gherkin example.

Buyers should not be able to fill invalid credit card details.

Versus

On the payment page, If a buyer enters a credit card number, that is not 16 digits of length, then when they try to proceed, it should give an error message pop up stating that the entered number is not correct.” 

The first Gherkin example is unclear and vague in comparison to the second one. Vagueness leads to errors and makes it harder for the tester to understand the requirement and implement test cases. 

Gherkin Syntax For Selenium Testing

The file structure in Gherkin is defined by the way different lines of code are indented in a feature file. Almost all lines in Gherkin for Cross Browser Testing start with a special keyword and line endings terminate statements which are called steps.

A Gherkin feature file is a combination of features, scenarios, and steps, which generally looks like this:

Plain Text
 







When executing the feature, the trailing portion of each step (after keywords like Given, And, When, etc) is matched to a regular expression, generally referred to as glue code that can be written in any language. In this tutorial, Java will be used.

Let us now walk through the above example to understand all the keywords.

Feature 

Feature keywords are used to donate a software feature. It usually contains a list of scenarios linked to that feature. Main elements of the feature are : 

  • The keyword – Feature.
  • The keyword, followed by the name user wants to give to the feature.
  • An optional description that can span multiple lines i.e. all the text between the line containing the keyword Feature, and a line that starts with Scenario or Background which is optional.

A good feature name should look something like :

In order to  <meet some goal> as a <type of user> I want <a feature> 

As a good Gherkin coding convention it is highly recommended that one feature makes up for one *.feature file which in the term is named by replacing spaces with an underscore and converting feature name to lowercase. Let’s take a Gherkin example,

Feature: In order to learn Gherkin as a beginner I want to study this tutorial

Feature file name: in_order_to_learn_gherkin_as_a_beginner_i_want_to_study_this_tutorial.feature

Background

It is usually used to add some context steps that are common to all scenarios and needs to run before each scenario in a single feature file. It is like an untitled optional scenario.

Plain Text
 




xxxxxxxxxx
1


 
1
Background : Given a customer named John  
2
    When clicks on buy now button  
3
    Then he should be redirected to payment page



Scenario

The scenario makes the core of Gherkin's structure. It describes the functionality that is under test. The main aim of a scenario is to be able to make the viewer understand what is being tested and how. The scenario keyword is followed by an optional title. 

One or multiple scenarios make up a feature file depending upon the feature in the test and one or multiple steps make up for a feature file.

By convention, a good scenario follows the following pattern

  • Describe an initial context using keyword Given
  • Describe an event using keyword When
  • Describe an expected outcome using the keyword Then.
Plain Text
 




xxxxxxxxxx
1


1
Scenario : John wants to automate Selenium with Gherkin  
2
     Given John wants to learn Gherkin  
3
     When He starts reading this tutorial  
4
     Then he is able to write feature file  



Steps

Steps basically make up the part of a scenario by means of given, when, then.

Given

The sole purpose of a Given statement is to give a context in order to establish a known state before the user starts interacting with the feature scenario under test.

When

This is used to describe the event due to user actions in a given state.

Then

The purpose of then step is to describe and analyse the outcomes. This analysis aims to add benefit to features by verifying the outcome that is or is not related to Given and When or may be to some external system.

But

These keywords are used to combine several Given, When or Then statements helping to make the scenario to be more readable and presentable.

Plain Text
 




xxxxxxxxxx
1


 
1
 Scenario : Understanding the steps  
2
      Given I establish a context  
3
      And I add another context  
4
      When I discuss them both  
5
      And I ask questions  
6
      Then I have no more doubts  
7
      But I have a better understanding  



How To Run Selenium Test Scripts Using Cucumber?

To make a gherkin project for Selenium Testing, the easiest way is to create a new maven project in any IDE like Eclipse. Also, the dependencies for Cucumber, Selenium, and Junit runners to execute the feature files.

for using Cucumber with java

Java
 




xxxxxxxxxx
1


1
<dependency>   
2
   <groupId>info.cukes</groupId>   
3
   <artifactId>Cucumber-java</artifactId>   
4
   <version>1.0.2</version>   
5
   <scope>test</scope>   
6
</dependency> 
7
 
          



for Selenium

Java
 




xxxxxxxxxx
1


 
1
<dependency>   
2
   <groupId>org.Seleniumhq.Selenium</groupId>   
3
   <artifactId>Selenium-java</artifactId>   
4
   <version>2.47.1</version>   
5
</dependency>  
6
 
          



For JUnit runner to run Cucumber features

Java
 




xxxxxxxxxx
1


 
1
<dependency>   
2
   <groupId>junit</groupId>   
3
   <artifactId>junit</artifactId>   
4
   <version>4.10</version>   
5
   <scope>test</scope>   
6
</dependency>  
7
 
          



Why Use Gherkin With Selenium Testing?

Selenium is a widely used tool for functional testing across top organizations as it is easy to integrate with Gherkin and makes understanding and automating of the flow both easy and possible to be done at the same time. 

By doing so one makes it easy to maintain test cases which also serves as proper documentation for all the Stakeholders and Analysts. Selenium is easy to integrate and a widely liked automation tool adds up to the usage of Cucumber. Together they make up a framework which is very easy to set up and has a low maintenance cost. 

Moreover, the ability to run feature files parallelly is another advantage. Also, both Gherkin and Selenium can be coded in Java for writing the glue code for steps and browser automation respectively.

Benefits Of Gherkin In Selenium Testing With Example

Here I will explain the usage of Gherkin for Selenium Testing with some examples and the framework along with file structure by means of the following example.

Let’s take a test scenario with the development of a web application for an organization, let’s say ’Shopping.com’, and the team is discussing a process flow of order placement by a customer.

First Step, for a customer to place an order, he/she should navigate to the website and log in. 

Plain Text
 




xxxxxxxxxx
1


1
Given Customer navigates to the website  
2
And Customer login to his account



After that customer searches for a product and clicks on add to cart button.

Plain Text
 




xxxxxxxxxx
1


1
When customer searches for laptop  
2
And clicks on add to cart button  



A customer reaches the cart page and is able to click the place order button

Plain Text
 




xxxxxxxxxx
1


1
Then Customer is redirected to cart page  
2
And Customer is able to click the place order button.  



After the flow is passed on to the automation tester, he uses it to write automation cases. Further, he adds automation code steps for the discussion file by converting it to a feature file.

Plain Text
 




xxxxxxxxxx
1


 
1
Feature : Place new order  
2
   As a customer, I want to place an order for searched item  
3
      Scenario : Place an order for the required product  
4
            Given Customer navigates to the website  
5
            And Customer login to his account  
6
            When customer searches for laptop  
7
            And clicks on add to cart button  
8
            Then Customer is redirected to cart page  
9
            And Customer is able to click the place order button  



Now to make these steps work I’ll write step definition code

Java
 




xxxxxxxxxx
1
28


1
package Cucumber.stepDefinitions;  
2
   
3
public class PlaceOrderStepDefs {  
4
      @Given(“Customer navigates to the website”)  
5
      public void navigateToWebsite(){  
6
      }  
7
      
8
      @And(“Customer login to his account”)  
9
      public void customerLogin(){  
10
      }        
11
      
12
      @When(“customer searches for laptop”)  
13
      public void searchForLaptop(){  
14
      }        
15
      
16
      @And(“clicks on add to cart button”)  
17
      public void clickAddToCart(){  
18
      }  
19
      
20
      @Then(“Customer is redirected to cart page”)  
21
      public void redirectionToCartPage(){  
22
      }  
23
      
24
      @And(“Customer is able to click the place order button”)  
25
      public void clickPlaceOrderButton(){  
26
      }  
27
}  
28
 
          



Now the point to note here is that there would be some data related to customers that are required and might be used by other feature files and scenarios as well. So it makes sense to create a separate file for such data called a properties file. 

Also, steps like loading this property file, initializing the driver, closing the browser after each scenario also need to be done and this would be common to all tests. So it makes sense to create a base steps file and inherit that to all step definition files.

Java
 




xxxxxxxxxx
1
12


1
#  APP        
2
url=http://www.shopping.com/   
3
   
4
#  Selenium      
5
webdriver.chrome.driver=resources/chromedriver  
6
   
7
#  CUSTOMER      
8
   
9
customerId=12345  
10
customerUsername=steven  
11
customerPassword=password123
12
 
          



BaseSteps.java

Java
 




xxxxxxxxxx
1
27


1
public class BaseTests {  
2
    public static WebDriver driver;  
3
    
4
      @BeforeClass  
5
      public static void initialiseDriverAndProperties() {  
6
            loadTestProperties();  
7
            driver = new ChromeDriver();  
8
            driver.manage().window().maximize();  
9
       }  
10
 
11
      @AfterClass  
12
      public static void closeBrowser() {  
13
            driver.quit();  
14
      }  
15
 
16
      private static void loadTestProperties(){  
17
            Properties properties = System.getProperties();  
18
            try {  
19
                  properties.load(  
20
                  new FileInputStream(new File("resources/test.properties")));  
21
            } catch(Exception ex) {  
22
                  ex.printStackTrace();  
23
                  System.exit(-1);  
24
            }  
25
      }  
26
}  
27
 
          



Having written BaseSteps.java and test.properties file now let us complete the step definition file

PlaceOrderStepDefs.java

Java
 




xxxxxxxxxx
1
37


1
package Cucumber.stepDefinitions;  
2
   
3
public class PlaceOrderStepDefs extends BaseSteps{  
4
      @Given(“Customer navigates to the website”)  
5
      public void navigateToWebsite(){  
6
            driver.get(System.getProperty(“url”));  
7
      }  
8
 
9
      @And(“Customer login to his account”)  
10
      public void customerLogin(){
11
            driver.findElement(By.id(“username”)).enterData(“username”);  
12
            driver.findElement(By.id(“password”)).enterData(“password”);  
13
            driver.findElement(By.id(“login”)).click();  
14
      }  
15
 
16
      @When(“customer searches for laptop”)  
17
      public void searchForLaptop(){  
18
            driver.findElement(By.id(“searchBox”)).enterData(“Laptop”);  
19
            driver.findElement(By.id(“searchButton”)).click();  
20
      }  
21
 
22
      @And(“clicks on add to cart button”)  
23
      public void clickAddToCart(){  
24
            driver.findElement(By.id(“addToCart”)).click();  
25
      }  
26
 
27
      @Then(“Customer is redirected to cart page”)  
28
      public void redirectionToCartPage(){  
29
            Assert.assertTrue(driver.findElement(By.id(“cartPageHeader”)).isDisplayed());  
30
      }  
31
 
32
      @And(“Customer is able to click the place order button”)  
33
      public void clickPlaceOrderButton(){  
34
            Assert.assertTrue(driver.findElement(By.id(“placeOrderButton”)).isClickable());  
35
      }  
36
} 
37
 
          



Finally, a step would be to a runner file to run this feature.

CucumberTestRunner.java

Java
 




xxxxxxxxxx
1
11


1
package Cucumber;  
2
  
3
@RunWith(Cucumber.class)  
4
@CucumberOptions(  
5
      plugin = {"pretty"},  
6
      glue = {"Cucumber.stepDefinitions"},  
7
      features = {"src/test/java/Cucumber/features"})  
8
   
9
public class CucumberTestRunner { 
10
}  
11
 
          



With this example, it is quite evident how easy it is to use Gherkin for Selenium Testing to make automation better.

Using Gherkin For BDD On Online Selenium Grid

In order to execute the Selenium automation over an Online Selenium Grid, you just need to update the BaseSteps.java to have the LambdaTest account username and access token along with few codes changes to let the system know that it will a RemoteWebDriver running on the Selenium grid URL with these capabilities.

Here’s what updated BaseSteps.java would look like

Updated BaseSteps.java

Java
 




xxxxxxxxxx
1
40


1
public class BaseTests {    
2
      
3
public static RemoteWebDriver driver;    
4
      
5
      @BeforeClass    
6
      public static void initialiseDriverAndProperties() {    
7
            loadTestProperties();    
8
            DesiredCapabilities capabilities = new DesiredCapabilities();  
9
           
10
            String username = "<your_lambdatest_username>";  
11
            String accesskey = "<your_lambdatest_accesstoken>";  
12
            String lambdaTestGridURL = "@hub.lambdatest.com/wd/hub";  
13
               
14
            capabilities.setCapability("build", "Selenium_Gherkin_Project");  
15
            capabilities.setCapability("name", "Placing order for a product");  
16
            capabilities.setCapability("platform", "Windows 10");  
17
            capabilities.setCapability("browserName", "chrome");  
18
            capabilities.setCapability("version", "73.0");  
19
            capabilities.setCapability("visual",false);    
20
            capabilities.setCapability("network",false);    
21
            capabilities.setCapability("console",false);    
22
            capabilities.setCapability("tunnel",false);  
23
            try {  
24
                  driver = new RemoteWebDriver(new URL("http://" + username + ":" + accesskey                     + lambdaTestGridURL), capabilities);  
25
            } catch (MalformedURLException e) {  
26
                  System.out.println("Invalid grid URL");  
27
            }   
28
      }    
29
       
30
      private static void loadTestProperties(){    
31
            Properties properties = System.getProperties();    
32
            try {    
33
                  properties.load(    
34
                  new FileInputStream(new File("resources/test.properties")));    
35
            } catch(Exception ex) {    
36
                  ex.printStackTrace();    
37
            }    
38
      }    
39
}  


Execute the test the same as earlier using the TestRunner file and you are good to go with added advantages of using the Selenium grid and get more information about the execution in a more presentable form.

Wrapping It Up

In this tutorial I explained how using a BDD framework like Cucumber with Gherkin can help in better collaboration among all the stakeholders along with the basics of Gherkin language and how to use its syntax. Then I went on to develop our first Selenium test automation script using Gherkin for Selenium Testing.

Now you know why you shouldn’t shy away from Gherkin for Selenium Testing. Also, how it can help all the stakeholders in your team have a strong understanding of the project. Thereby helping the project achieve its business goals faster. Happy Testing!!

Topics:
automation testing, gherkin syntax, java, selenium - web browser automation, selenium automated testing

Published at DZone with permission of Rahul Rana . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}