kroe761 kroe761 - 4 years ago 87
Java Question

Access variable in @BeforeTest and @AfterClass (TestNG) across separate classes?

I am writing some selenium automated UI tests for my company using Java and the TestNG framework. I am defining the driver in a

class, and I want to actually initialize the driver in an
and quit it in a
method. What is the Java way to do that, assuming they are in different classes? I know how to make it work in the same class, but not over separate classes. Here is my

public class Base {

public static WebDriver driver = null;
public WebDriver getDriver() {
driver = new ChromeDriver();
return driver;

Now, I want to have a separate Setup class and a separate Teardown class. If I was going to define all of this in the same
, I would do it this way:

public void testOne() {

Base b = new Base();
WebDriver driver = b.getDriver();

// Do test-y things here.


How would I set this up? Trying to learn the right way to do this, and not hack something together. I can also provide more information if needed. Thanks!

Answer Source

Use inheritance.

public class TestBase {

    protected WebDriver driver;

    public void setUp(){
        System.out.println("I am in setUp method.");

        //WebDriver instantiation etc.
        System.setProperty("", "/path/to/chromedriver");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized", "--disable-cache");
        driver = new ChromeDriver(options);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    public void tearDown(){
        System.out.println("I am in tearDown method.");

        //You can clean up after tests.

And then inheritance can be used. Pay attention to the extends keyword:

public class ParticularTest extends TestBase {

   public void testMethod() {
       System.out.println("I am in testMethod.");

       //Your driver from TestBase is accessible here.
       //Your assertions come here.

Later on you can just execute Output:

I am in setUp method.
I am in testMethod.
I am in tearDown method.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download