Search code examples
javaseleniumcucumberhook

Pass Webdriver from @Before hook to Cucumber step


I have such hook

public class GeneralHook {
    DriverManager driverManager;
    WebDriver driver;
    ConfigFileReader configFileReader = new ConfigFileReader();

    @Before
    public void before(Scenario scenario) {
        System.out.println("Hook before");
        String browser = System.getProperty("BROWSER");
        if (browser == null) {
            browser = System.getenv("BROWSER");
            if (browser == null) {
                browser = "chrome";
            }
        }
        switch (browser) {
            case "firefox":
                driverManager = DriverManagerFactory.getManager(DriverType.FIREFOX);
                driver = driverManager.getDriver();
                driver.get(configFileReader.getApplicationUrl());
                break;
            case "chrome":
            default:
                driverManager = DriverManagerFactory.getManager(DriverType.CHROME);
                driver = driverManager.getDriver();
                driver.get(configFileReader.getApplicationUrl());
                break;
        }
    }

And i need to pass driver from this hook to Step class of Cucumber. Is that somehow possible? Thank you.


Solution

  • Yes my friend. It is possible with the help of Dependency injection like cucumber picocontainer with the help of that you will able to share the state of the Java class to other classes. Please find the reference link below.

    http://www.thinkcode.se/blog/2017/04/01/sharing-state-between-steps-in-cucumberjvm-using-picocontainer