Search code examples
javaseleniummavencucumbertestng

How to use correctly TestNG annotations with Cucumber framework


I am building TestNG and Cucumber framework, and want to use TestNG annotations like @BeforeMethod, @AfterMethod which will run setUp and tearDown methods before and after each scenario. It works fine if I keep all my Cucumber scenarios in separate feature files. But if I have multiple scenarios in the same feature file @AfterMethod is not running after each scenario.

Also have issues if using cucumber Before and After, they work fine only if I put them in StepDefinition file below:

public class StepDefinition extends Base {
    
    @Before
    public void setUp() throws Exception {
        openBrowser();
        maximizeWindow();
//      implicitWait(30);
        deleteAllCookies();
//      setEnv();
    }
    
    @After
    public void quit() throws IOException, InterruptedException {
        driver.quit();
    }

    @Given("^Navigate to ACT landing page$")
    public void navigate_to_ACT_landing_page() throws Throwable {
        LandingPage landingPage = new LandingPage();
        landingPage.navigateToLandingPage();
    }

    @Then("^Verify landing page is rendered$")
    public void verify_landing_page_is_rendered() throws Throwable {
        LandingPage landingPage = new LandingPage();
        landingPage.landingPageRendered();
    }

}

But if I put them in separate class (like below) they don't work (in documentation says that they can be put anywhere in the project)

package com.act.hooks;


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

import java.io.IOException;

import com.moodys.act.base.Base;

public class Hooks extends Base {
    
    @Before
    public void setUp() throws Exception {
        openBrowser();
        maximizeWindow();
//      implicitWait(30);
        deleteAllCookies();
//      setEnv();
    }
    
    @After
    public void quit() throws IOException, InterruptedException {
        driver.quit();
    }

}

Solution

  • Cucumber does not recommend to prepare and clean states using TestNG annotations. In order to take maximum benefits of TestNG, you can try using pure TestNG implementation for BDD with QAF. It considers each scenario as TestNGMethod.

    If you want to use cucumber then you can add qaf-cucumber dependency and use TestNG factory. It will allow to use TestNG listeners and lifecycle methods (@BeforeMethod, @AfterMethod). When using cucumber with qaf you can choose either to utilize TestNG life-cycle or cucumber life-cycle.

    Furthermore, if you are working with webdriver or appium it has inbuilt thread-safe driver management so you don't need to worry about driver management.