Saturday, April 22, 2023

 

What is BDD in selenium?

What is BDD

BDD (Behavior Driven Development) is software development approach that allows developer or tester to create the script base on the behavior or functionality of the application.

The steps of behavior or functionality, user write in feature file in plain English language which is called as “Gharkin” language. This help a common user understand the scenarios which are covered for specific functionality.

In BDD, user write scenario in feature file and the implementation of those scenarios will be mentioned in the form of code in step definition which is also called as glue code.

How to write BDD test cases in cucumber?

There are 3 important components for writing test case in cucumber.

Feature file:-

Feature file is used to write a scenarioes with its steps in plain English language. This file can be created with extension ".feature". User can write multiple scenarios and can pass multiple parameters to single scenario. There can be multiple feature file in one project based on the functionality.

Step definition:-

This is use to write the implementation of the steps mentioned in feature file. This is a java class where user writes the methods for each steps.

Runner Class:-

This class is used to execute a script. It has Junit annotations such as

@runwith, which is the starting point of execution.

@cucumberoptions, which is use to do required configuration such as path of feature file, path of glue code etc…

Step in Feature file

    Feature: This is my first feature
    Background:
    Given Launch the website
    @test
     Scenario Outline: I want to launch shoping url
    
    Given user logged in to website                     

Step definition

@Given("^user logged in to website$")
 
 public void already_login() 
 {
 System.out.println("Thisis Given");

 }

Test Runner Class

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

@RunWith(Cucumber.class)
@CucumberOptions(
		features = {"src/test/java/org/feature"},
		glue = {"org.Teststep"}	,
		tags= "@test",
		monochrome = true
		)

Cucumber runner class maven dependency

    <dependency>
            <groupId>io.cucumber </groupId>
            <artifactId>cucumber-java </artifactId>
            <version>6.10.4 </version>
            <scope>test </scope>
     </dependency>

      <dependency>
            <groupId>io.cucumber </groupId>
            <artifactId>cucumber-junit </artifactId>
            <version>6.10.4 </version>
             <scope>test </scope>
      </dependency>

     <dependency>
            <groupId>junit </groupId>
            <artifactId>junit </artifactId>
            <version>4.13.2 </version>
             <scope>test </scope>
     </dependency>
        

 

Test Runner class

Test runner class is the starting point in BDD from where the script get executed with the help of junit annotation. Test runner class use junit class annotation which is @Runwith(). This gets execution once we execute the script. There is one another annotation with the name @cucumberOptions. This is use to do some configuration before running the script.

Some options are given below.

a) features:- This option is used to provide the feature file path.

b) glue:- This option is used to provide the step definition file path.

c) tags:- This option is used to provide the tag name in feature file. With the help of this it will execute only those scripts which will match to these tags. In general, we may have many scenarios such as regression, functional or sanity scenario in feature file. This can be executed separately by using tag name.

We can use “and “, “or “,”not” operator while writing tag name. Example given below.

tags= "not @test# This will run scenario other than tag name @test from feature file.

tags= "@test and @test1" #This will run the scenario which have both the tag name “@test” and “@test1” from feature file.

tags= "@test or @test1" # This will run all the scenario which has tag name “@test” or “@test1” in feature file. See below example.

        //tags= "not @test",
		//tags= "@test and @test1"
		//tags= "@test1 or @test"
        

d) Monochrome:- This option is to print the output on console in readable format. The value should be set to true for this. This can have true or false value.

e) Strict:- This option is used to check if any method is missing in step definition file. And if any step is not defined then it will stop the execution of program. This can have true or false value.

f) dryRun:- This option is used to check if all the steps are defined in step definition file or not. The value of this option should be set as true to check if all the steps are defined in step definition or not. Once it is verified that all the steps are defined then the value can be set as false.

g) Plugin/Format: - This option is use to specify different formatting options to show output report. The reports are generally created in HTML format or Json format. See below example.

For HTML format
plugin= {"pretty","html:target/cucumber-reports/index.html"},

For json formate
plugin= {"pretty","json:target/cucumber-reports/Cucumber.json"}

Runner class

import org.junit.runner.RunWith; import io.cucumber.junit.Cucumber; import io.cucumber.junit.CucumberOptions; @RunWith(Cucumber.class) @CucumberOptions( features = {"src/test/java/org/cuck"}, glue = {"org.Teststep"} , //plugin= {"pretty","html:target/cucumber-reports/index.html"} plugin= {"pretty","json:target/cucumber-reports/Cucumber.json"} , tags= "not @test", //tags= "@test and @test1" //tags= "@test1 or @test" dryRun = true, monochrome = true ) public class RunnerTest { }

Cucumber runner class maven dependency

    <dependency>
            <groupId>io.cucumber </groupId>
            <artifactId>cucumber-java </artifactId>
            <version>6.10.4 </version>
            <scope>test </scope>
     </dependency>

      <dependency>
            <groupId>io.cucumber </groupId>
            <artifactId>cucumber-junit </artifactId>
            <version>6.10.4 </version>
             <scope>test </scope>
      </dependency>

     <dependency>
            <groupId>junit </groupId>
            <artifactId>junit </artifactId>
            <version>4.13.2 </version>
             <scope>test </scope>
     </dependency>
        


 

What Is Hooks In Cucumber?

Hooks in Cucumber

Hooks is nothing but the script which run before or after each scenarios. There are some annotation which are used to execute script before or after each scenarioes.

Below are the lists of cucumber annotation which can use in BDD.

1. @Before:-
This annotation is same like @BeforeMethod annotation in TestNG. This annotation invoke before each test case in feature file.Example is given below.

Step definition

@Before
	public void beforeAnnotation()
	{
		System.out.println("This is before Annotation");
	}
      

2. @Before(order =1):-
In case, if you have more than one before annotation in one class then this will arrange the order of before annotation Example is given below.

Step definition

  
  @Before (order=0)
	public void beforeOrderMethod0()
	{
		System.out.println("Before Order 0");
	}
    
@Before (order=1)
	public void beforeOrderMethod()
	{
		System.out.println("Before Order 1");
	}
    
    
    

3. @BeforeStep:-
This annotation will execute before each step in feature file. Example is given below.

Step definition

 
@BeforeStep
	public void beforeStep()
	{
		System.out.println("this will execute before each step");
	}
    

4. @After:-
This annotation is same like @AfterMethod annotation in TestNG. This annotation invoke after each test case in feature file. Example is given below.

Step definition

  
    @After
	public void AfterMethod()
	{
		System.out.println("This is After Method");
	}
    

5. @After(order=2):-
In case, if you have more than one after annotation in one class then this will arrange the order of after annotation. Example is given below.

Step definition

  
   
   @After (order=0)
	public void AfterOrderMethod0()
	{
		System.out.println("After Order 0");
	}
    
    
@After (order=1)
	public void AfterOrderMethod()
	{
		System.out.println("After Order 1");
	}
    

6. @AfterStep:-
This annotation will execute after each step in feature file. Example is given below.

Step definition

     
@AfterStep
	public void afterStep()
	{
		System.out.println("this will execute after each step");
	}

 

Regular expression in step definition

Regular Expression

Below are some lists of special character that can be used while writing step definition.

1. .(dot)-We can use any character in place of "." In below example, single step definition will work for both the steps mentioned in feature file. It will replace "." with "e" and "o" as mentioned in steps.

  
    
Feature StepsStep Definition
Then This is red Then This is rod@Then("^This is r.d$")

2. * (star) - "*" is use to repeat the same char. In below example, we can repeat "l" one or many time. Steps Step Definition

  
    
Feature StepsStep Definition
Thenyou are wellll text @Then("^you are wel* text$")


3. .* - "." is use for any char and "*" is for repeat the char. In below example, any char can be entered up to any length.

  
    
Feature StepsStep Definition
ThenThis is my book text @Then("^This is my bo.* text$")

4. (+) (plus sign)-"+" is used to avoid any empty string. In below example, "b" and "r" can be repeat multiple times. It will show error when the entered char is other than "b" or "r" or empty.

  
    
Feature StepsStep Definition
Then make a brbat @Then("^make a [br]+at$")

5. (.+)- "." is use for any char and "+" is for avoiding empty string. In below example, “.” Can be replacing with any char. So here any char can be entered up to any length.

  
    
Feature StepsStep Definition
Then I make new bat @Then("^I make new .+at$")

6. (\d or [0-9])- This will accept only one digit between [0-9] and no empty string. See the below example.

  
    
Feature StepsStep Definition
Then The roll number is 3 @Then ("^The roll number is (\\d)$") or @Then("^The roll number is [0-9]$")

7. (\d+ or [0-9]+)- This will accept one or more than one digit between [0-9]. In below example, we have entered 2 digits.

  
    
Feature StepsStep Definition
Then This is my book 31 @Then ("^This is my book (\\d+)$") or @Then ("^This is my book [0-9]+$")

8. [a-f]- "[a-f]" it will accept any one char between “a” To “f”. So it will restrict the char base on given range. See the below example.

  
    
Feature StepsStep Definition
Then This is limit to alpha b @Then ("^This is limit to alpha [a-f]$") OR For accepting number and char, see the step definition as below. @Then ("^This is limit to alpha [0-9a-cA-C]$")


9. [ea]- Any char mentioned in square bracket only those char can be used. This will accept either "e" or "a". Any char enter other than this will throw error. In below example, single step definition will work for both the steps.

  
    
Feature StepsStep Definition
Then This is blua OR Then This is blue @Then ("^This is blu[ea]$")

10. .{2}- This will accept exact 2 char. Anything entered less or more than 2 will throw error. In below example, 2 size limit is given in step definition.

  
    
Feature StepsStep Definition
Then This is two char ab @Then ("^This is two char .{2}$")

11. .{2,4}- Here the minimum length is 2 and Maximum length is 4. So anything entered less than 2 or more than 4 will give error. In below example, min length given as 2 and Max as 4 in step definition.

  
    
Feature StepsStep Definition
Then This is limit to four char abc @Then ("^This is limit to three char .{2,4}$")

12. \w- This will accept [A-Za-z0-9_] any alpha, number or underscore. In below example, we have given underscore between “s” and “w”.

  
    
Feature StepsStep Definition
Then This is my word s_w @Then ("^This is my word s[\\w]w(.*)$")

13. ? (question sign) – This anchor is use to make preceding char as optional. In below example, here "u" kept as optional. So "?" mark before any char will be optional. In feature file we can pass "color" or "colour". It will work for both.

  
    
Feature StepsStep Definition
Then This is color @Then ("^This is colou?r$")


14. |(pipe line) - This "|" pipe line is like “or” condition. We can give multiple words in pipe line as or option. For example, in feature file we can have two different steps, then a single step definition will work for both the steps.

  
    
Feature StepsStep Definition
Then he has taken book OR Then Then she has taken book @Then ("^This is colou?r$")

15. ^(caret sign) - "^" This anchor is used to exclude the char mentioned in square bracket. In below example, if you enter "s" or "n", it will throw error. For rest other char, it will work fine. "^" this anchor also indicate that the line start from there and $ indicate the end of line.

  
    
Feature StepsStep Definition
Then This is greep @Then ("^This is gree[^sn]$")

16. $ - "$" indicate end of line. ^ and $ use for exact string match. Ex.. I'm logged in will match I'm logged in with admin, I'm logged in with editor. But if we use "^" at the start and "$" at end. It treat all three step different.

  
    
Feature StepsStep Definition
Then This is greep @Then ("^This is gree[^sn]$")


17. \"(.*)\" - (.*) will take value and display as "open" however \"(.*)\" will take value within "" comma such as "open" will be taken as open. In below example, method will receive word as open instead of “open”.

  
    
Feature StepsStep Definition
Then school is "open" @Then ("^school is \\\"(.*)\\\"$")

18. {String} - {string} is used to pass the string from feature file. But "^" and "$" cannot be used at the start and end of the line. See the below example.

  
    
Feature StepsStep Definition
Then gate is "closed" @Then ("gate is {string}")

19. {int} - {int} is used to pass the integer value from feature file to methods. But "^" and "$" cannot be used at the start and end of the line.

  
    
Feature StepsStep Definition
Then flat number is 7 @Then ("flat number is {int}")

20. {float} - {float} is used to pass the float value from feature file to methods. But "^" and "$" cannot be used at the start and end of the line.

  
    
Feature StepsStep Definition
Then float value is 7.67 @Then ("float value is {float}")

21. ()- When you write any regular expression with parentheses, it becomes a capture group. In a Cucumber Step Definitions, the text matched within each capture group is passed to the code block as an argument. In below example (.*), this will pass the value to code block.

  
    
Feature StepsStep Definition
Then This is number <char> @Then ("^This is number(.*)$")

 

How to pass the Parameter?

Passing parameter by using “” (double quotes) OR <> sign

From feature file, we can pass a single parameter by using “” in the step.Example is given below.

Step in Feature file

 Given user logged with "userID"
 

We can also repeat the same step with different parameter by using “Scenario Outline” and “Example” keywords. In below example, a single step will repeat 2 times with 2 different inputs parameter. Scenario will repeat for all the parameter we mentioned in “Examples” keyword.

Step in Feature file

Feature: This is my first feature
Scenario Outline: This shopping scenario
When user select item <number>

Examples:
|number|
|one|
|two|

Step definition (This step definition can used for above both the feature file examples)

@When("^user select item (.*)$")
public void navigate_to_home_page2(String number) {
System.out.println(number);
	}
    

Passing group of conditions in Step definition.

Some time we have to pass a group of condition in step definition. Example is given below.

Step in Feature file

Then apple is sweet
    

Step definition

@Then (“^(?:apple|mango|cherry) is sweet$”)

public void apple_is_sweet() {
System.out.println("fruits");	
}

Passing the list of parameter from feature file.

pipe (|) line can also be used for passing lists of items in specific test step. Example is given below.

Step in Feature file

    
 And the lists are given below:
|Laptop|
|Kitchen|
|home_Appliances|

     

Step definition

    
@And("the list are given below:(.*)")
    
public void ListOfItem(List<String> list) {
System.out.println(list);
	}

    
    

 

How to write step definition in cucumber?

Java class is used for writing step definition file. This execute each given steps in feature file. We have to write a method for each step in step definition java class with same annotation and with the same steps given in feature file. Each step associate to one method which get executed.

Annotation is step definition

Below are the lists of annotations which are generally used in feature file and same are used in step definition.
@Given
@When
@Then
@And
@But

While writing step definition, we have to make sure the steps written in feature file, it should be same in step definition. Such as example given below.

Step in Feature file

 Given This is a book

Step definition

    
@Given (“^This is a book$”)
Public void method1()  
{
System.out.println(“test”);
}

Note: - Method name can be anything, but it’s better to have method name as per the steps.

“^”sign indicate the start of text and “$” sign indicate the end of text. These anchors are used to make our test step unique. If we are not using this anchors then 2 matching steps will be consider as same steps.



 

BDD cucumber Secondary keywords in feature file

Secondary keywords in feature file


Below are some lists of secondary keywords which can be use in feature file while writing test case.

1. # (hash sign): -

hash(#) is used to comment the line in feature file. So for commenting any line in feature file, we can put # before the start of the line.

2. @ (at the rate of): -

@ is used for mentioning the tag name in feature file. Tag name is use for running a specific scenario in feature file. This can be at feature level, scenario level, Examples level and etc. One scenario can have multiple tag names. Example is given below.

#Here hash is used to comment this line.
@e2e  @regression
Feature: This is my first feature file
@smoke
Scenario Outline: This is scenario outline with example keyword
When Enter customer name <name>
@test 
Examples:
|name|
|kabir|
|khan|

3. | (pipe line sign):-

In “Examples” keyword, pipe (|) line is used for entering multiple fields test data in the steps. This also used for passing lists of items in specific test step. Example is given below.

Passing list parameters in cucumber from feature file to step definition.

Step in Feature file

And the lists are given below:
|Laptop|
|Kitchen|
|home_Appliances|

Step definition

@And("the list are given below:(.*)")
	public void ListOfItem(List<String> list) {
	    System.out.println(list);
	}
    

Passing parameters in cucumber feature file in step definition.

Step in Feature file

When Enter customer name <name>

@example
Examples:
|name|
|kabir|
|khan|

Step definition

@When("^Enter customer name (.*)$")
	public void enter_CustomName(String name) {
	   System.out.println("Scenario outline :- "+name);
	}
      

4. “”” (Three inverted comma):-

This symbol is used for putting large or multiple line text in the steps. Example is given below.

Step in Feature file

    
Then user able to see the large text:
"""
Below are the list of items which can be selected
user can select any value
"""

Step definition

    
@Then("user able to see the large text:(.*)")
	public void largeText(String text) {
	    System.out.println(text);
	}
    

5. “” (Double inverted comma):-

Double inverted comma is used to passing test data in the step. Example is given below.

Step in Feature file

Given user logged with "userID"
    

6. <> (greater than less than sign) :-

This is used for passing the reference of test data in test step from feature file. Example is given below.

Step in Feature file

And user select also select item <item>
    

Step definition

    
@And("^user select also select item ([^\\\"]*)$")
	public void navigate_to_home_page3(String Items) {
	    System.out.println(Items);
	}
    

7. “<>” (greater than less than sign with inverted comma):-

This also used for passing the reference of test data in the test step. Example is given below.

Step in Feature file

When user select item "<number>"
    

Step definition

@When("^user select item \\\"(.*)\\\"$")
	public void navigate_to_home_page2(String number) {
	    System.out.println(number);
	}
    

 

Selenium BDD cucumber Keywords in Feature file


Keywords in Feature file

Feature file is use to write the test step in Gherkin language. Below are some important keywords in feature file which are used to write test case.

•	Background
•	Feature
•	Scenario/Example
•	Scenario outline
•	Examples

Background: -

Background keywords in cucumber are used, when we have some common step in each scenario, which need to be executed every time. So instead of writing those common steps in each scenario every time, we can use Background keyword which will execute the background step before each scenario. Background: Given Gmail url launched

Feature: -

Feature keyword is use to describe the feature of the scenario. You can have multiple feature files base on the story or requirement. And you can have multiple scenarios in one feature file. Feature: This is my first feature file

Scenario/Example: -

Scenario as its name indicate, it talk about scenario of that feature. With scenario key work you can execute only one scenario with single parameter Scenario: This is scenario Given user logged with "userID"

Scenario outline: -

scenario outline is used to execute same scenario with different parameter. We can use “Examples” keyword to pass the parameter. We can pass the reference of the parameter Examples: - Examples keyword is use to send the parameter in scenario step. See below example.

Feature: This is my first feature file
Background:
Given Gmail url launched
@login
Scenario Outline: This is scenario outline with example keyword
When Enter customer name <name>
Examples:
|name|
|kabir|
|khan|
Out come :-

This is Backgroud Annotation Scenario outline :- kabir This is Backgroud Annotation Scenario outline :- khan

In above example, Background keyword will execute after each scenario. With the help of scenario outline and Examples keyword we can pass the parameter.




Translate

Popular Posts

Total Pageviews