Share WebDriver instance in Cucumber using PicoContainer

Share WebDriver instance in Cucumber using PicoContainer

In our previous article we discussed how we can share data between step definitions using dependency injection.

In this article we will use the same constructor injection technique to share web driver instances in multiple step definitions using PicoContainer.

For demo, in one step definition we will visit programsbuzz and in another step definition we will click on login link.

Step 1: Add Pico Container dependency from here

<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-picocontainer</artifactId>
    <version>7.2.1</version>
</dependency>

Step 2: Create Base.Java class and add following code:

public class Base 
{
    private WebDriver driver;
	
    public WebDriver getDriver()
    {
        return driver;
    }
	
    public void setDriver()
    {
        System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "//drivers//chromedriverm");

        driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.manage().window().maximize();
    }
}

Step 3: Create Hook.Java class and add following code

public class Hooks
{
    WebDriver driver;
    Base base;
	
    public Hooks(Base base)
    {
        this.base = base;
    }
	
    @Before
    public void bf()
    {
        base.setDriver();
    }
	
    @After
    public void af()
    {
        base.getDriver().quit();
    }
}

Step 4: create Test.feature file

@tag
Feature: Title of your feature

  @demo
  Scenario: Title of your scenario
  When I visit the homepage
  And I click on login link

Step 5: Create First.Java step definition file and add your first step definition

public class FirstSD 
{
    WebDriver driver;
    Base base;
	
    public FirstSD(Base base)
    {
        this.base = base;
    }
	
    @When("I visit the homepage")
    public void i_visit_the_homepage()
    {
        base.getDriver().get("https://www.programsbuzz.com");
    }
}

Step 6: Create Second.Java step definition file and add step to click on login

public class SecondSD 
{
    WebDriver driver;
    Base base;
	
    public SecondSD(Base base)
    {
        this.base = base;
    }
	
    @When("I click on login link")
    public void i_click_on_login_link()
    {
        base.getDriver().findElement(By.linkText("LOG IN")).click();
    }
}

Execute your code and verify the code running or watch video below to see it working.

Video Tutorial: Cucumber Sharing WebDriver Instance using Pico Container

Standard (Image)