- Similar to Background keyword. But Hooks have more advantages than Background keyword.
- Hooks in Cucumber are special blocks of code that run before or after each scenario. They are defined in the step definition classes and help in managing test setup and teardown.
@Before
→ runs before each scenario@After
→ runs after each scenario
- Before Hooks will execute
- Check any background and will execute
- then scenario will execute
- After hooks will execute
✅ Tagged Hooks (Conditional Hooks)
Run a hook only for scenarios with a specific tag:
1. Feature File – login.feature 📁 src/test/java/features/login.feature Feature: Application Login @Smoke Scenario: Login with valid credentials Given user is on login page When user logs in with "admin" and "1234" Then homepage is displayed
//This feature file outlines a single scenario where a user logs in with valid credentials.
//The @Smoke tag indicates that this is a smoke test, which is a preliminary test to check the basic functionality.
✅ 2. Step Definitions – LoginSteps.java
📁 src/test/java/stepDefinitions/LoginSteps.java
package stepDefinitions;
import io.cucumber.java.en.*;
public class LoginSteps {
@Given("user is on login page")
public void user_is_on_login_page() {
System.out.println("Step: User is on login page");
}
@When("user logs in with {string} and {string}")
public void user_logs_in_with_credentials(String username, String password) {
System.out.println("Step: Logging in with Username: " + username + " | Password: " + password);
}
@Then("homepage is displayed")
public void homepage_is_displayed() {
System.out.println("Step: Homepage is displayed");
}
}
✅ 3. Hooks Class – Hooks.java
📁 src/test/java/stepDefinitions/Hooks.java
package stepDefinitions;
import io.cucumber.java.Before;
import io.cucumber.java.After;
public class Hooks {
@Before
public void setUp() {
System.out.println("Hook: Launching Browser...");
}
@After
public void teardown() {
System.out.println("Hook: Closing Browser...");
}
}
//The Hooks class contains methods that run before and after each scenario.
//The setup method is where you would typically initialize your WebDriver, while the teardown method handles cleanup.
✅ 4. TestNG Runner – TestNGRunner.java 📁 src/test/java/cucumberOptions/TestNGRunner.java package cucumberOptions; import io.cucumber.testng.AbstractTestNGCucumberTests; import io.cucumber.testng.CucumberOptions; @CucumberOptions( features = "src/test/java/features", glue = "stepDefinitions", monochrome = true, plugin = { "pretty", "html: target/cucumber-report.html" }, tags = "@Smoke" ) public class TestNGRunner extends AbstractTestNGCucumberTests { } ✅ Console Output (Expected) Hook: Launching Browser... Step: User is on login page Step: Logging in with Username: admin | Password: 1234 Step: Homepage is displayed Hook: Closing Browser...