Cucumber - Before and After Hooks

Cucumber - Before and After Hooks

Cucumber provides @Before and @After hooks to execute specific code before and after each test scenario. These hooks are widely used for tasks such as setting up test environments, initializing resources, or cleaning up after tests. By centralizing such tasks, they help improve the structure and efficiency of the test framework.

What Are Before and After Hooks?

Before Hooks: These are executed before every scenario to ensure the necessary preconditions are in place. After Hooks: These are executed after every scenario to clean up or reset the environment.

Hooks can also be ordered using priorities, allowing you to specify the sequence in which multiple hooks should run.

Example: Full Program Demonstrating Before and After Hooks

Let's consider an example where we use Cucumber to test a web application's login functionality.

Step Definitions File (Hooks.java)

                  
                    package com.example.tests;
              
                    import io.cucumber.java.Before;
                    import io.cucumber.java.After;
              
                    public class Hooks {
              
                        @Before
                        public void setUp() {
                            System.out.println("Setting up the browser and initializing resources...");
                            // Example: Code to initialize WebDriver, set timeouts, etc.
                        }
              
                        @After
                        public void tearDown() {
                            System.out.println("Closing the browser and cleaning up resources...");
                            // Example: Code to close WebDriver, clear cookies, etc.
                        }
                    }
                  
                

Feature File (LoginFeature.feature)

                  
                    Feature: User Login
                      Test login functionality for valid and invalid scenarios.
              
                      Scenario: Successful login with valid credentials
                        Given the user is on the login page
                        When the user enters valid credentials
                        Then the user should be redirected to the dashboard
              
                      Scenario: Unsuccessful login with invalid credentials
                        Given the user is on the login page
                        When the user enters invalid credentials
                        Then an error message should be displayed
                  
                

Step Definitions File (LoginSteps.java)

                  
                    package com.example.tests;
              
                    import io.cucumber.java.en.Given;
                    import io.cucumber.java.en.When;
                    import io.cucumber.java.en.Then;
              
                    public class LoginSteps {
              
                        @Given("the user is on the login page")
                        public void userOnLoginPage() {
                            System.out.println("Navigating to the login page...");
                            // Code to navigate to the login page
                        }
              
                        @When("the user enters valid credentials")
                        public void userEntersValidCredentials() {
                            System.out.println("Entering valid credentials...");
                            // Code to enter valid username and password
                        }
              
                        @When("the user enters invalid credentials")
                        public void userEntersInvalidCredentials() {
                            System.out.println("Entering invalid credentials...");
                            // Code to enter invalid username and password
                        }
              
                        @Then("the user should be redirected to the dashboard")
                        public void userRedirectedToDashboard() {
                            System.out.println("Verifying redirection to the dashboard...");
                            // Code to verify successful login
                        }
              
                        @Then("an error message should be displayed")
                        public void errorMessageDisplayed() {
                            System.out.println("Verifying error message...");
                            // Code to verify error message for unsuccessful login
                        }
                    }
                  
                

Test Runner File (TestRunner.java)

                  
                    package com.example.tests;
              
                    import io.cucumber.testng.AbstractTestNGCucumberTests;
                    import io.cucumber.testng.CucumberOptions;
              
                    @CucumberOptions(
                        features = "src/test/resources/features",
                        glue = "com.example.tests"
                    )
                    public class TestRunner extends AbstractTestNGCucumberTests {
                        // No additional code required; Cucumber handles execution
                    }
                  
                

Real-World Use Cases

Below are some examples of how Before and After Hooks can be used in real-world scenarios:

  • E-commerce Testing:
    • Before Hook: Create a new test user and log them in before the scenario starts.
    • After Hook: Delete the test user and clear the cart after the scenario ends.
  • Database Testing:
    • Before Hook: Seed the database with test data.
    • After Hook: Rollback changes or clear test data to maintain a clean state.
  • API Testing:
    • Before Hook: Set up authentication tokens and request headers.
    • After Hook: Log API responses and clean up any temporary resources.

Benefits of Before and After Hooks

  • Eliminates repetitive code by centralizing setup and teardown actions.
  • Improves test maintainability and readability.
  • Ensures consistent preconditions and cleanups across scenarios.