Hooks in Cucumber

HOME

In this tutorial, I will explain about Hooks in Cucumber.

What is Hook in Cucumber?

Hooks are blocks of code that can run at various points in the Cucumber execution cycle. They are typically used for setup and teardown of the environment before and after each scenario. These hooks do not impact the scenarios or steps for which they are used. We can declare hooks in any class.

Why do we use Hooks?

There are scenarios where we have to perform some pre-requisite steps before executing the test scenarios, like initiating a WebDriver, setting up database connection, setting up Test Data, setting up browser cookies.

Similarly, there are some conditions that needs to be done after completing the execution of test scenarios like Killing the webdriver, closing database connections, clearing the test data, clearing browser cookies and so on.

Scenario hooks

Scenario hooks run for every scenario. There are 2 type of Scenario Hooks – @After and @Before

Before
Before hooks run before the first step of each scenario.

Syntax:

@Before
	public void setup() {

		System.out.println("--------------------Before Executing----------------------");
		System.setProperty("webdriver.chrome.driver",
				"C:\\Users\\SingVi04\\Desktop\\SeleniumKT\\chromedriver_win32\\chromedriver.exe");
		driver = new ChromeDriver();
	}

After
After hooks run after the last step of each scenario, even when the step result is failed, undefined, pending, or skipped.

Syntax:

@After
	public void close() {
		driver.close();
		System.out.println("---------------After Executing---------------------------");
	}

Here is an example of Hooks – @Before and @After in a Cucumber program.

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import io.cucumber.java.After;
import io.cucumber.java.AfterStep;
import io.cucumber.java.Before;
import io.cucumber.java.BeforeStep;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;

public class CucumberHooksExampleDefinitions {

	WebDriver driver;

	@Before
	public void setup() {

		System.out.println("------------------Before Executing-------------------------");
		System.setProperty("webdriver.chrome.driver",
				"C:\\Users\\SingVi04\\Desktop\\SeleniumKT\\chromedriver_win32\\chromedriver.exe");
		driver = new ChromeDriver();
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	@Given("User is on Home page")
	public void userOnHomePage() {
		System.out.println("Open Website");
		driver.get("https://opensource-demo.orangehrmlive.com/");
	}

	@When("User enters username as {string}")
	public void entersUsername(String userName) throws InterruptedException {
		Thread.sleep(1000);
		System.out.println("Enter userName");
		driver.findElement(By.name("txtUsername")).sendKeys(userName);
	}

	@When("User enters password as {string}")
	public void entersPassword(String passWord) throws InterruptedException {		 
        System.out.println("Enter passWord");
		driver.findElement(By.name("txtPassword")).sendKeys(passWord);
		driver.findElement(By.id("btnLogin")).submit();
	}

	@Then("User should be able to login sucessfully")
	public void sucessfullLogin() throws InterruptedException {
		String newPageText = driver.findElement(By.id("welcome")).getText();
		System.out.println("newPageText:" + newPageText);
		assertThat(newPageText, containsString("Welcome"));
	}

	@After
	public void close() {
		driver.close();
		System.out.println("--------------------After Executing-----------------------");
	}
}
  1. At the start of execution, @Before annotation is setting up the web driver to execute the test.
  2. After setting up web driver, the Given, When and Then statements will be executed.
  3. Now at the last, @After hook will close the web driver.

Step hooks

Step hooks invoked before and after a step. The hooks have ‘invoke around’ semantics. Meaning that if a BeforeStep hook is executed the AfterStep hooks will also be executed regardless of the result of the step.

@BeforeStep – As the name suggests, it is executed before the execution of each step.

Syntax:

@BeforeStep
	public void beforeStepTest() {
		System.out.println("--------------BeforeStep Executing---------------");
	}

@AfterStep – As the name suggests, it is executed after the successfull execution of each step. If a step did not pass, the following step and its hooks will be skipped.

Syntax:

@AfterStep
	public void afterStepTest() {
		System.out.println("--------------------AfterStep Executing---------------------");
	}
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import io.cucumber.java.After;
import io.cucumber.java.AfterStep;
import io.cucumber.java.Before;
import io.cucumber.java.BeforeStep;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;

public class CucumberHooksExampleDefinitions {

	WebDriver driver;

	@Before
	public void setup() {

		System.out.println("---------------------Before Executing----------------------");
		System.setProperty("webdriver.chrome.driver",
				"C:\\Users\\SingVi04\\Desktop\\SeleniumKT\\chromedriver_win32\\chromedriver.exe");
		driver = new ChromeDriver();
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	@BeforeStep
	public void beforeStepTest() {
		System.out.println("--------------BeforeStep Executing---------------");
	}

	@Given("User is on Home page")
	public void userOnHomePage() {

		System.out.println("Open Website");
		driver.get("https://opensource-demo.orangehrmlive.com/");
	}

	@When("User enters username as {string}")
	public void entersUsername(String userName) throws InterruptedException {

		System.out.println("Enter userName");
		driver.findElement(By.name("txtUsername")).sendKeys(userName);

	}

	@When("User enters password as {string}")
	public void entersPassword(String passWord) throws InterruptedException {

		System.out.println("Enter passWord");
		driver.findElement(By.name("txtPassword")).sendKeys(passWord);

		driver.findElement(By.id("btnLogin")).submit();
	}

	@Then("User should be able to login sucessfully")
	public void sucessfullLogin() throws InterruptedException {

		String newPageText = driver.findElement(By.id("welcome")).getText();
		System.out.println("newPageText:" + newPageText);
		assertThat(newPageText, containsString("Welcome"));

	}

	@AfterStep
	public void afterStepTest() {
		System.out.println("--------------------AfterStep Executing---------------------");
	}

	@After
	public void close() {
		driver.close();
		System.out.println("--------------------After Executing----------------------");
	}
}
  1. At the start of execution, @Before annotation is setting up the web driver to execute the test.
  2. After setting up web driver, @BeforeStep is executed before executing first step.
  3. After the execution of first step (Given), @AfterStep is executed.
  4. Here, it can be seen that there are 4 steps and for each step there is a combination of @BeforeStep and @AfterStep.

One thought on “Hooks in Cucumber

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s