top of page

Cucumber Hooks

​

​

What Are Hooks In Cucumber ?

​

Hooks are the blocks of code that run before and after each scenario. It can be defined in step-definition.It enables us to manage the code workflow and also to reduce the code redundancy.

​

'@Before' and '@After' are the hooks in cucumber.We can add multiple hooks in step-definition and the default execution of hooks is in alphabetical order. 

 

Let's understand it with an example :

  • Step-definition :

​

package stepdefinitions;

import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.cucumber.java.en.Given;

public class HooksExample {
   
   @Before
   public void beforeScenario() {
       System.out.println("\nThis will run before each scenario");
   }
   
   @After
   public void afterScenario() {
       System.out.println("This will run after each scenario\n");
   }
   
   @Given("^Run step of scenario 1$")
   public void run_Scenario_I() throws Throwable {
       System.out.println("Runnig step of Scenario 1");
   }

    @Given("^Run step of scenario 2$")
   public void run_Scenario_II() throws Throwable {
       System.out.println("Runnig step of Scenario 2");

    }

    

}

​

 

  • Feature file :

​

Feature: Hooks Example


  Scenario: Scenario 1 is included
    Given Run step of scenario 1
   
  Scenario: Scenario 2 is included
    Given Run step of scenario 2
    

 

package cucumberTest;

import org.junit.runner.RunWith;

import io.cucumber.junit.Cucumber;

​

​

  • Test Runner Class :

​

@RunWith(Cucumber.class)
@io.cucumber.junit.CucumberOptions(
       features = "Features/featureTag.feature"
       ,glue={"stepdefinitions"} 
       )

​

public class TestRunnerForHooks {

}

 

​

Output :

 

This will run before each scenario
Runnig step of Scenario 1
This will run after each scenario


This will run before each scenario
Runnig step of Scenario 2
This will run after each scenario

 

 

 

 

Refer next page Tagged Hooks In Cucumber

​

bottom of page