Skip to main content

Cucumber: Sharing WebDriver instance 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.

Submitted by tgoswami on January 12, 2022

Tarun has 11+ years of experience in Quality Assurance in different domains like Banking, E-commerce, Health and Education.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.