Using TestNG to drive WebDriver tests
by Eing Ong
- opens browser only on the first test run
- close browser only when all tests have finished running
- tests can be run in eclipse and can reuse the same browser when running multiple tests at a time
- maven and testng.xml file reuses 1 browser for all tests
There is common suggestion to add setup to suite.xml but this approach will not work in eclipse when you run a test package for example. It's also cumbersome to run/edit suite.xml all the time as you usually want to run only a few files. So here's another way to solve it.
1. Create a base test class.
@Test(groups = { "functionaltest" } )
public class BaseTest
{
public WebDriver driver;
public Element elementDriver;
@BeforeClass
public void setupBeforeClass() throws InterruptedException
{
// get a driver or browser
driver = InitBrowserTest.getDriver();
elementDriver = new Element(driver);
}
}
2. Create a singleton test called InitBrowserTest. This will create and close the browser.
@Test(groups = {"init"} )
public class InitBrowserTest
{
private static WebDriver driver;
public static WebDriver getDriver()
{
if (driver == null)
{
driver = new FirefoxDriver();
// Initialize driver or run headless
driver.get("https://gmail.com");
// Login and setup for all tests here
return driver;
}
@AfterGroups
@Test
public static void teardownAfterGroups()
{
// This will close the browser after all tests are completed
driver.quit();
}
3. If you use testng.xml (such as dailytests.xml)
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Daily Tests" verbose="10">
<test name="Functional Tests">
<groups>
<run>
<include name="init" />
<include name="functionaltest" />
<exclude name="broken" />
</run>
</groups>
<packages>
<package name="com.google.test.functional.*" />
</packages>
</test>
</suite>
Subscribe via RSS