Sharing selenium Webdriver instance using PicoContainer in Cucumber

In Selenium automation, we create a WebDriver instance. But we can not use the same driver instance in different step definition classes in Cucumber.

We can share the same Webdriver instance in 2 ways.

  1. By creating a static Webdriver
  2. By using PicoContainer (Dependency Injection)

First method is very simple. Just create a class with Static WebDriver field.

Now let us take a look at how we can share the same driver using Dependency Injection. For this, you will need below dependencies.



Next, we need to create a class where we will create a Webdriver instance as shown in below example. Note that we instantiates the driver only once. We have got a method getDriver to get the driver.

package org.softpost;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SharedClass {

    private static boolean startBrowser = false;

    private WebDriver driver;
    public String title = "";

    public void init() throws Exception {
        if (!startBrowser) {

          driver = new FirefoxDriver();

            //To stop launching browser after every scenario, assign below variable with true value
            startBrowser = false;

    public WebDriver getDriver() {
        return driver;

    public void cleanUp() {


Next in the step definition classes, we can pass the instance of above class as shown in below example. Note that we are using getDriver() method to access the driver instance. So similarly you can pass the instance of SharedClass to any step definition class that wants to use the driver. PicoContainer is used internally to wire up dependent classes.

package org.softpost;

import junit.framework.Assert;

public class ShareSeleniumSteps {

    SharedClass sharedClass;

    public ShareSeleniumSteps(SharedClass sharedClass){
        this.sharedClass = sharedClass;

    @Given("^I am on the www\\.softpost\\.org home page$")
    public void i_am_on_the_www_softpost_org_home_page() throws Throwable {


    @Then("^I verify that title contains tutorials$")
    public void i_verify_that_title_contains_tutorials() throws Throwable {
        Assert.assertTrue(  sharedClass.getDriver().getTitle().toLowerCase().contains("tutorials"));

    @Then("^I verify that title contains tutooorials$")
    public void i_verify_that_title_contains_tutooorials() throws Throwable {
        Assert.assertTrue(  sharedClass.getDriver().getTitle().toLowerCase().contains("tutooorials"));


You may also like...