Hooks in Cucumber

Introduction: 

Hooks in cucumber are the setup and teardown methods that can be written in a configuration class separately or in a step definition class. Hooks are useful when we have multiple scenarios and every scenario needs to be executed with the same setup and teardown steps. We can either code the common steps into the scenarios or create a common function for setup and teardown and annotate those functions with ‘@before’ and ‘@after’ annotations, it helps to avoid rewriting the common setup and teardown actions into our scenarios and steps. Hooks can run before and after every scenario, it can also run before and after each step in a scenario, and it can be associated with tags for conditional execution.  

In this blog, we will discuss- 

  • Project setup for using hooks in cucumber 
  • How to create & use Hooks in cucumber
  • Conditional Hooks 

Project setup for using hooks in cucumber 

Firstly, we must install all prerequisites in our project (for more info about prerequisites you can visit- Web automation using Selenium and Cucumber with Java

Add the maven dependencies: 

After verifying the prerequisites, add the required dependencies as shown below 

To get the maven dependencies first we need to visit the link below: 

https://mvnrepository.com/repos/central  and then we need to search for the required dependency 

Project setup for Hooks in cucumber code

Select Cucumber JUnit>click on the latest version>copy the dependency 

> add it to the pom.xml file 

Similarly, we need to search for Cucumber JVM:JUnit(io.cucumber)> Select Cucumber JVM:JUnit(io. cucumber) >click on the latest version>copy the dependency 

Cucumber jvm

> add it to the pom.xml file 

Next, we need to search for WebDriverManager(io.github.bonigarcia)>click on the latest version>copy the dependency 

Webdriver manager

> add it to the pom.xml file 

Lastly, we need to search for Selenium Java(org.seleniumhq.selenium)>Select Java(org.seleniumhq.selenium)> click on the latest version>copy the dependency 

> add it to the pom.xml file 

Below is an image of the pom.xml file after all the dependencies have been added 

Hooks in cucumber code

How to create & use Hooks

In order to use tags, we first need to create a feature file. 

To create a new feature file, right-click on the Features folder in ‘src/test/resources’> click on New> go to File>provider File name with ‘.feature’ extension> click on Finish 

Features

 In the below image, a feature file with the name ‘HooksDemo’ has been created. 

Hooks in cucumber code

Next, we need to create the features, scenarios for the features, and the steps to follow for the specific feature as per the scenario. 

Feature: Check login functionality 
  Scenario:
      Given user is on login page 
      When user enters valid username
      And user enters valid password 
      And clicks on the sign in button 
      Then user navigates to the home page 
  
Hooks demo feature

Code explanation:  

In this example, we have a feature file containing the title of the feature as Check login functionality, and a scenario followed by the Steps given by using Given, When, Then, And which will instruct the process for testing the particular feature. 

After creating the feature file, we need to create a step definition class, in order to provide a backend code for the steps that we have written in the feature file so that the processor will know the exact code to be executed through the step definition for each step that we have created in the feature file. 

To add the Step Definitions/Glue Code> right click on src/test/ java package> go to New> select Folder>Provide the name of the folder>click on Finish 

New folder

After creating the Steps folder right click on it> go to New> select class> provide the name of the class>click on Finish 

New java class

Next, we need to run the feature file and then copy the provided functions for ‘Given, When, And, Then’ under the message stating to implement the missing steps from the console and paste it into the class created in the Step Definitions folder. 

package Steps; 
import io.cucumber.java.en.And; 
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then; 
import io.cucumber.java.en.When; 
public class HooksDemoSteps { 
      @Given("user is on login page") 
      public void user_is_on_login_page() { 
      } 
      @When("user enters valid username") 
      public void user_enters_valid_username() { 
 
      } 
      @And("user enters valid password") 
      public void user_enters_valid_password() { 
      } 
      @And("clicks on the sign in button")
      public void clicks_on_the_sign_in_button() { 
 
      } 
       @Then("user navigates to the home page") 
       public void user_navigates_to_the_home_page() { 
      } 
} 
Hooks in cucumber code

To run the tests using the selenium web driver we need to do the following:

Go to the step definition class and write the code that will execute the test using selenium on the browser as shown below 

package Steps; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.chrome.ChromeDriver; 
import io.cucumber.java.After; 
import io.cucumber.java.AfterStep; 
import io.cucumber.java.Before; 
import io.cucumber.java.BeforeStep; 
import io.cucumber.java.en.And; 
import io.cucumber.java.en.Given; 
import io.cucumber.java.en.Then; 
import io.cucumber.java.en.When; 
import io.github.bonigarcia.wdm.WebDriverManager; 
public class HooksDemoSteps { 
      WebDriver driver = new ChromeDriver(); 
      @Before 
      public void setup() { 
           WebDriverManager.chromedriver().setup(); 
           driver.manage().window().maximize(); 
      } 
      @After 
      public void teardown() { 
           driver.close(); 
           driver.quit(); 
      } 
      @BeforeStep 
      public void beforeSteps() { 
            System.out.println("Before Steps"); 
      } 
       @AfterStep 
       public void afterSteps() { 
            System.out.println("After Steps"); 
       } 
       @Given("user is on login page") 
       public void user_is_on_login_page() { 
       } 
        @When("user enters valid username") 
        public void user_enters_valid_username() { 
        } 
        @And("user enters valid password") 
        public void user_enters_valid_password() { 
        } 
        @And("clicks on the sign in button") 
        public void clicks_on_the_sign_in_button() { 
        } 
         @Then("user navigates to the home page") 
         public void user_navigates_to_the_home_page() { 
        } 
}  
Hooks in cucumber code

Code explanation: 

In the above code, we have declared the web driver variable at class level so that it can be used in every function of the class, and created a setup function in order to launch the chrome browser by using ‘WebDriverManager.chromedriver().setup();’ and  ‘driver.manage().window().maximize();’ to maximize the window before starting the test and provided ‘@Before’ annotation to make the setup function as a hook to be executed before every scenario.  

Next, we created a teardown function in order to close the browser using ‘driver.close();’ and quit the browser using ‘driver.quit();’ and provided ‘@After’ annotation to make the teardown function as a hook to be executed after every scenario. 

We have also created a ‘beforeSteps’ function in order to execute it before each step of the scenarios and provided ‘@BeforeStep’ annotation to make the ‘beforeSteps’ function as a hook to be executed before every step of the scenarios. 

Lastly, we have created an ‘afterSteps’ function in order to execute it after each step of the scenarios and provided ‘@AfterStep’ annotation to make the ‘afterSteps’ function as a hook to be executed after every step of the scenarios. 

Conditional Hooks 

We can run scenarios that belong to a specific tag in the feature file, by adding the tag name to the annotations in step definitions class functions. 

package Steps; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.chrome.ChromeDriver; 
import io.cucumber.java.After; 
import io.cucumber.java.AfterStep; 
import io.cucumber.java.Before; 
import io.cucumber.java.BeforeStep; 
import io.cucumber.java.en.And; 
import io.cucumber.java.en.Given; 
import io.cucumber.java.en.Then; 
import io.cucumber.java.en.When; 
import io.github.bonigarcia.wdm.WebDriverManager; 
public class HooksDemoSteps { 
    WebDriver driver = new ChromeDriver(); 
    @Before("@regression") 
    public void setup() { 
        WebDriverManager.chromedriver().setup(); 
        driver.manage().window().maximize(); 
    } 
    @After 
    public void teardown() { 
        driver.close(); 
        driver.quit(); 
    } 
     @BeforeStep 
     public void beforeSteps() { 
         System.out.println("Before Steps"); 
    } 
     @AfterStep 
     public void afterSteps() { 
         System.out.println("After Steps"); 
    } 
     @Given("user is on login page") 
     public void user_is_on_login_page() { 
    } 
     
     @When("user enters valid username") 
     public void user_enters_valid_username() { 
     } 
     @And("user enters valid password") 
     public void user_enters_valid_password() { 
     } 
     @And("clicks on the sign in button") 
     public void clicks_on_the_sign_in_button() { 
     } 
     @Then("user navigates to the home page") 
     public void user_navigates_to_the_home_page() { 
     } 
  
} 
Hooks in cucumber code

Code explanation: 

In the above code, we have annotated the setup function with ‘@Before(“@regression”)’ which will run the setup function only for the regression tag scenarios. Similarly, we can provide conditions for @After, @BeforeStep, and @AfterStep hooks. 

Execution and results: 

To execute the feature file we need to create a runner class .

To create a runner class we need to right-click on the steps folder>go to new> select class> provide the name of the class>click on Finish 

New java class

After Creating the test runner class file, we need to add the cucumber annotation and options. And provide the location of the feature files and step definitions as shown below: 

package Steps; 
import org.junit.runner.RunWith; 
import io.cucumber.junit.Cucumber; 
import io.cucumber.junit.CucumberOptions;
@RunWith(Cucumber.class) 
@CucumberOptions(features="src/test/resources/Features",glue= {"Steps"}) 
public class TestRun { 

} 
 
Hooks in cucumber code

To run the test runner class file, we need to right-click on the class file> select Run As> select JUnit Test. 

After executing the test runner class, we should get JUnit results as passed as shown in below image: 

Result