top of page

Cucumber Tutorial

Execution Order Of Hooks

What Is The Execution Order Of Hooks ?

Hooks execute in alphabetical order by default but we can set the order of these hooks execution as cucumber provides such feature. Setting order of execution means setting priority to each hook. We can set priorty for each hook by using a parameter 'order' and assigning an integer value to it. But the difference is that for:
  • @Before - It runs in increment order that means the lower integer hook would run first : @Before(order=1)

  • @After - It runs in decrement order which means the higher integer hook would run first : @After(order=1)


Here's an example to demonstrate it :

  • Step-definition :

package stepdefinitions; import io.cucumber.java.After; import io.cucumber.java.Before; import io.cucumber.java.en.Given; ​ public class HooksOrderExample { @Before(order=2) public void A() { System.out.println("A will run before each scenario"); } @Before(order=1) public void B() { System.out.println("\nB will run before each scenario"); } @After(order=1) public void C() { System.out.println("C will run after each scenario\n"); } @After(order=2) public void D() { System.out.println("D will run after each scenario"); } @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: Execution Order Of Hooks Example Scenario: Scenario 1 is included Given Run step of scenario 1 Scenario: Scenario 2 is included Given Run step of scenario 2

  • Test Runner Class :

package cucumberTest; import org.junit.runner.RunWith; import io.cucumber.junit.Cucumber; ​ @RunWith(Cucumber.class) @io.cucumber.junit.CucumberOptions( features = "Features/featureTag.feature" ,glue={"stepdefinitions"} ) ​ public class TestRunnerForHooksOrder { } ​ ​ Output : B will run before each scenario A will run before each scenario Runnig step of Scenario 1 D will run after each scenario C will run after each scenario B will run before each scenario A will run before each scenario Runnig step of Scenario 2 D will run after each scenario C will run after each scenario



bottom of page