0% found this document useful (0 votes)
7 views

Cucumber Hooks

The document explains the implementation of hooks in Cucumber, specifically @Before and @After hooks for setting up and tearing down test scenarios. It provides code examples for initializing a WebDriver before tests and closing it afterward, as well as step-level hooks for logging and taking screenshots. Additionally, it covers the structure of feature files, step definitions, and a test runner for executing the tests.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Cucumber Hooks

The document explains the implementation of hooks in Cucumber, specifically @Before and @After hooks for setting up and tearing down test scenarios. It provides code examples for initializing a WebDriver before tests and closing it afterward, as well as step-level hooks for logging and taking screenshots. Additionally, it covers the structure of feature files, step definitions, and a test runner for executing the tests.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Implement hooks

Hooks in Cucumber

In a test execution, there will be blocks of code that always need to be run to set up (prerequisite
tasks) and tear-down (post-run tasks) the related test artifacts like machine settings, browser
states, etc.

The Java implementation of Cucumber provides two entities which are called hooks. They
are @Before and @After. As the name suggests, Methods/functions/pieces of code defined
within:

 @Before hooks will be run before the first step of each scenario under the feature
 @After hooks will be run after the last step of each scenario under the feature

Hooks are defined within the step definition file only.


The basic syntax for writing the hooks is shown here:

1.
2. package utilities;
3. import cucumber.api.java.After;
4. import cucumber.api.java.Before;
5.
6. public class Hooks {
7.
8. @Before
9. public void beforeScenario(){
10. System.out.println("This will run before the Scenario");
11. }
12.
13. @After
14. public void afterScenario(){
15. System.out.println("This will run after the Scenario");
16. }

17. }

Things to keep in mind:

 An important thing to note about the @after hook is that it will run even in case of the
test fails, undefined scenarios or skipped steps inside the scenarios.

 The method name for hooks can be anything, need not be beforeScenario() or
afterScenario(), always. You can use method names for hooks as, setUp() and
tearDown().

 Make sure that the package import statement should be imported


cucumber.api.java.After; & import cucumber.api.java.Before;

Now let look at a demo for the standard hooks - @Before and @After.

What are Hooks in Cucumber?

Cucumber provides hooks (@Before, @After, @BeforeStep, @AfterStep) to execute


preconditions and postconditions before/after scenarios or steps. These are useful for test
setup, cleanup, logging, screenshots, reporting, and database connections.
1️@Before & @After Hooks (Basic Example)

📌 Use Case:

 @Before: Opens the browser before each scenario.


 @After: Closes the browser after each scenario.

Hooks Implementation (@Before & @After)

We will initialize the WebDriver before each scenario and close the browser after the scenario
execution.

package hooks;

import io.cucumber.java.After;
import io.cucumber.java.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Hooks {


private static WebDriver driver;

@Before
public void setup() {
System.out.println("Launching browser...");
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
driver = new ChromeDriver();
driver.manage().window().maximize();
}

@After
public void teardown() {
System.out.println("Closing browser...");
if (driver != null) {
driver.quit();
}
}

public static WebDriver getDriver() {


return driver;
}
}
2 Login Feature File (Scenario using URL)
2️⃣

📝 features/Login.feature

Feature: Swag Labs Login

Scenario: User logs in with valid credentials


Given User is on the Swag Labs login page
When User enters username "standard_user" and password "secret_sauce"
Then User should be logged in successfully

3️⃣Step Definitions for Login Scenario

📝 stepDefinitions/LoginSteps.java

package stepDefinitions;

import hooks.Hooks;
import io.cucumber.java.en.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;

public class LoginSteps {


WebDriver driver = Hooks.getDriver();

@Given("User is on the Swag Labs login page")


public void user_is_on_login_page() {
driver.get("https://www.saucedemo.com/");
}

@When("User enters username {string} and password {string}")


public void user_enters_valid_credentials(String username, String password) {
driver.findElement(By.id("user-name")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.id("login-button")).click();
}

@Then("User should be logged in successfully")


public void user_should_be_logged_in_successfully() {
String expectedUrl = "https://www.saucedemo.com/inventory.html";
Assert.assertEquals(driver.getCurrentUrl(), expectedUrl);
}
}
4️⃣Cucumber Test Runner

📝 runner/TestRunner.java

package runner;

import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;

@CucumberOptions(
features = "src/test/resources/features",
glue = {"stepDefinitions", "hooks"},
)
public class TestRunner extends AbstractTestNGCucumberTests {
}

@BeforeStep & @AfterStep Hooks (Step-Level Execution)

📌 Use Case:

 @BeforeStep: Runs before every step (useful for logging).


 @AfterStep: Runs after every step (useful for taking screenshots).

Real-World Use Case for @BeforeStep & @AfterStep Hooks in Cucumber

We will implement step-level hooks for logging and capturing screenshots after each step
while automating the Swag Labs login process.

📌 URL: https://www.saucedemo.com/

1️⃣Implementing @BeforeStep & @AfterStep Hooks with Screenshot Capture

📝 hooks/Hooks.java

package hooks;

import io.cucumber.java.*;
import org.openqa.selenium.*;
import org.openqa.selenium.io.FileHandler;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Hooks {


private static WebDriver driver;

@Before
public void setup() {
System.out.println("Launching browser...");
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
driver = new ChromeDriver();
driver.manage().window().maximize();
}

@BeforeStep
public void beforeStep() {
System.out.println("🔹 Before Step Hook Executed");
}

@AfterStep
public void afterStep(Scenario scenario) {
System.out.println("🔹 After Step Hook Executed");
if (scenario.isFailed()) {
captureScreenshot(scenario.getName());
}
}

@After
public void teardown() {
System.out.println("Closing browser...");
if (driver != null) {
driver.quit();
}
}

public static WebDriver getDriver() {


return driver;
}

public void captureScreenshot(String scenarioName) {


TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String destination = "screenshots/" + scenarioName.replaceAll(" ", "_") + "_" + timestamp
+ ".png";

try {
FileHandler.copy(source, new File(destination));
System.out.println("📸 Screenshot saved: " + destination);
} catch (IOException e) {
System.out.println("⚠️Error saving screenshot: " + e.getMessage());
}
}
}

2️⃣Feature File (Scenario with URL)

📝 features/Login.feature

Feature: Swag Labs Login with Step-Level Hooks

Scenario: User logs in with valid credentials


Given User is on the Swag Labs login page
When User enters username "standard_user" and password "secret_sauce"
Then User should be logged in successfully

📌3️⃣Step Definitions for Login Scenario

📝 stepDefinitions/LoginSteps.java

package stepDefinitions;

import hooks.Hooks;
import io.cucumber.java.en.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;

public class LoginSteps {


WebDriver driver = Hooks.getDriver();

@Given("User is on the Swag Labs login page")


public void user_is_on_login_page() {
driver.get("https://www.saucedemo.com/");
}

@When("User enters username {string} and password {string}")


public void user_enters_valid_credentials(String username, String password) {
driver.findElement(By.id("user-name")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.id("login-button")).click();
}

@Then("User should be logged in successfully")


public void user_should_be_logged_in_successfully() {
String expectedUrl = "https://www.saucedemo.com/inventory.html";
Assert.assertEquals(driver.getCurrentUrl(), expectedUrl);
}
}

📌4️⃣Cucumber Test Runner

📝 runner/TestRunner.java

package runner;

import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;

@CucumberOptions(
features = "src/test/resources/features",
glue = {"stepDefinitions", "hooks"},
)
public class TestRunner extends AbstractTestNGCucumberTests {
}
1️Feature File with Login Scenario (Login.feature)

📁 File: src/test/resources/features/Login.feature

Feature: Swag Labs Login

Scenario: Valid Login


Given User is on the Swag Labs login page
When User enters valid credentials
Then User should be logged in successfully

Scenario: Invalid Login


Given User is on the Swag Labs login page
When User enters invalid credentials
Then User should see an error message
Contains Two Scenarios:

1. Valid Login (standard_user / secret_sauce)


2. Invalid Login (invalid_user / invalid_pass)

2️⃣ Hooks Implementation (Hooks.java)

📁 File: src/test/java/hooks/Hooks.java

package com.automation.stepDefinitions;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.automation.runner.TestNGRunner;

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

public class Hooks {

public static WebDriver driver;

@Before
public void setup() {
String browser=TestNGRunner.browser;
String url=TestNGRunner.appUrl;

switch(browser.toLowerCase()) {
case "edge":
webDriver=new EdgeDriver();
break;
case "chrome":
webDriver=new ChromeDriver();
break;
case "firefox":
webDriver=new FirefoxDriver();
break;
default :
throw new IllegalArgumentException(browser+" Browser not supported");
}
webDriver.get(url);

@After
public void tearDown() {
webDriver.close();
}
}

1️⃣pages/LoginPage.java (Using Page Factory)

package pages;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class LoginPage {


WebDriver driver;

// Constructor
public LoginPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}

// Locators using Page Factory


@FindBy(id = "user-name")
private WebElement username;

@FindBy(id = "password")
private WebElement password;

@FindBy(id = "login-button")
private WebElement loginButton;

// Actions
public void enterUsername(String user) {
username.sendKeys(user);
}
public void enterPassword(String pass) {
password.sendKeys(pass);
}

public void clickLogin() {


loginButton.click();
}
}

4️⃣stepDefinitions/LoginSteps.java

package stepDefinitions;

import hooks.Hooks;
import io.cucumber.java.en.*;
import org.openqa.selenium.WebDriver;
import pages.LoginPage;
import org.testng.Assert;

public class LoginSteps {


WebDriver driver = Hooks.getDriver();
LoginPage loginPage = new LoginPage(driver);

@Given("User is on the Swag Labs login page")


public void user_is_on_login_page() {
driver.get("https://www.saucedemo.com/");
}

@When("User logs in with username {string} and password {string}")


public void user_enters_valid_credentials(String username, String password) {
loginPage.enterUsername(username);
loginPage.enterPassword(password);
loginPage.clickLogin();
}

@Then("User should be logged in successfully")


public void user_should_be_logged_in_successfully() {
Assert.assertEquals("https://www.saucedemo.com/inventory.html", driver.getCurrentUrl());
}
}
6️⃣runner/TestRunner.java (Test Runner Class)

package com.automation.runner;

import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;

import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;

@CucumberOptions(
features = "src/test/resources/features/HooksDemo.feature", // Path to feature files
glue = "com.automation.stepDefinitions" // Step definitions package

)
public class TestNGRunner extends AbstractTestNGCucumberTests{
public static String browser;
public static String appUrl;

@BeforeTest
@Parameters({"browser","url"})
public void setup(String browserParam, String urlParam) {
browser=browserParam;
appUrl=urlParam;

7 testng.xml (Passing Browser Parameter)


7️⃣
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Swag Labs Cucumber Test Suite">
<test name="Cucumber Tests">
<parameter name="browser" value="chrome"/>
<parameter name="url" value="https://petstore.octoperf.com/actions/Catalog.action"/>
<classes>
<class name="com.automation.runners.TestNGRunner"/>
</classes>
</test>
</suite>

You might also like