Testing / Cucumber Interview Questions
What are hooks in Cucumber?
Hooks are blocks of code that run at defined points around a scenario's execution, independent of any specific Gherkin step, used for cross-cutting setup and teardown concerns like opening a browser, starting a database transaction, or capturing a screenshot on failure.
@Before public void setUp() { driver = new ChromeDriver(); } @After public void tearDown(Scenario scenario) { if (scenario.isFailed()) { byte[] screenshot = ((TakesScreenshot) driver) .getScreenshotAs(OutputType.BYTES); scenario.attach(screenshot, "image/png", "failure-screenshot"); } driver.quit(); }
The main hook types are @Before and @After, running once per scenario, and @BeforeStep/@AfterStep, running around every individual step within a scenario. Hooks can also be tagged, so a hook only runs for scenarios matching a specific tag expression, rather than unconditionally for every scenario in the suite.
More Related questions...