Search code examples
javaseleniumtestng

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 Base class, and I want to actually initialize the driver in an @BeforeTest and quit it in a @AfterTest 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 Base.java file:

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 @Test, I would do it this way:

@Test
public void testOne() {

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

    // Do test-y things here. 

    driver.quit();
}

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!


Solution

  • Use inheritance.

    public class TestBase {
    
        protected WebDriver driver;
    
        @BeforeClass
        public void setUp(){
            System.out.println("I am in setUp method.");
    
            //WebDriver instantiation etc.
            System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--start-maximized", "--disable-cache");
            driver = new ChromeDriver(options);
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        }
    
        @AfterClass
        public void tearDown(){
            System.out.println("I am in tearDown method.");
    
            //You can clean up after tests.
            driver.close();
        }
    }
    

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

    public class ParticularTest extends TestBase {
    
       @Test
       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 ParticularTest.java. Output:

    I am in setUp method.
    I am in testMethod.
    I am in tearDown method.