Pages

What is Cucumber Hooks File ?

What is Cucumber Hooks File?

Cucumber Hooks:
  • Cucumber Hooks plays a vital role in the execution of cucumber scenarios.
  • It provides a block of code that will be used for setup and teardown of the environment before and after each scenario.
  • Cucumber provides annotation @Before and @After in order to execute a block of code
@Before Annotation:
  • The code we write in @Before annotation will be executed before the execution of all scenarios.
  • In @Before annotation, we write code for setup the environment like Web driver setup, launch browser, browser maximize, open the DB connections, etc.,.
  • Get the currently executing scenario name
  • We can use also use Hooks(@Before,@After) in any class.
@After Annotation:
  • The code we write in @After annotation will be executed after the execution of all scenarios.
  • In @After annotation, we write code for the teardown of environment like close the driver, quit the driver, close DB connections, taking screenshots, taking test reports, etc.,.
  • Get the status of the currently executed scenario.
  • We can use also use Hooks(@Before,@After) in any class.
Cucumber Hooks
Cucumber Hooks

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

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.IOException;

public class Hooks {

    public static WebDriver driver;
    @Before
    public void LaunchBrowser(Scenario s) {
        ChromeOptions chromeOptions = new ChromeOptions();
        System.setProperty("webdriver.chrome.driver", "D:\\drivers\\chromedriver.exe");
        System.out.println("started " + s.getName() + " execution");
        driver = new ChromeDriver(chromeOptions);
        driver.get("https://keeplearners.blogspot.com/");
        driver.manage().window().maximize();
    }

    @After
    public void scenarioexecuted(Scenario s) throws IOException {
        if (s.isFailed()) {
            byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
            s.attach(screenshot, "image/png", s.getName());
        }
        driver.quit();
    }
}
Note: we can give any class name in place of Hooks.
Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.