Dean Barnes
Dean Barnes

Reputation: 2272

Sharing a WebDriver instance when using Selenium, TestNG, and Cucumber-JVM

I am trying to add Cucumber-JVM to a TestNG and Selenium project I've been working on, where I currently re-use browsers on a grid via a testsuite something like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Grid" thread-count="2" parallel="tests">
    <test name="Firefox 27.0">
        <parameter name="browser" value="Firefox"/>
        <parameter name="browser_version" value="27.0"/>
        <packages>
            <package name="[Test package name]"/>
        </packages>
    </test>
    <test name="IE 11">
        <parameter name="browser" value="IE"/>
        <parameter name="browser_version" value="11.0"/>
        <packages>
            <package name="[Test package name]"/>
        </packages>
    </test>
</suite>

Each test class in the package then takes the parameters in a setUp method in the base class which looks like this:

@BeforeClass
@Parameters({"browser", "browser_version"})
public void setUp(String browser, String browser_version) throws MalformedURLException {
    // Do the setup with WebDriver and assign to an object property
}

However, I'd like to have a static or injected class that is shared between all the test classes to avoid re-initialising the browser each time, which should also let me share the WebDriver instance between the various step definition files. Does anyone know how to do this?

Upvotes: 2

Views: 3289

Answers (1)

Matthew Wilson
Matthew Wilson

Reputation: 2065

You could use Pico Container, which is packaged with Cucumber-JVM.

Then in the constructor of your test classes you can ask for the Driver:

public class TestClass {

    WebDriver driver;

    public TestClass(WebDriver driver) {
        this.driver = driver;
    }
}

PicoContainer will automatically pass an instance of the webdriver to the class, any other classes that have a similar constructor will also get the same instance.

Link to the documentation: http://picocontainer.codehaus.org/constructor-injection.html

Upvotes: 1

Related Questions