Please tell me sample code for the fallowing scenario using Web-driver + TestNG framework.
One class having the multiple tests. While running these tests it should run all the tests as parallel in multiple instances of same browser (Ex: Firefox) at a time. So for every test it should open a new instance of a browser.
My solution so far has been something like this:
public MyTestClass {
SupportedBrowser browser;
private static ThreadLocal<WebDriver> threadLocalDriver = new ThreadLocal<WebDriver>();
@DataProvider (name = "getBrowsers")
public Object[][] getBrowsers {
return Object[][] {
{
SupportedBrowser.FIREFOX;
},
{
SupportedBrowser.CHROME;
}
};
}
@Factory (dataProvider = "getBrowsers")
public MyTestClass(SupportedBrowser browser) {
this.browser = browser;
}
@BeforeMethod
public void setup()
{
threadLocalDriver.set(browser.getDriver());
}
@Test
public void test1()
{
WebDriver driver = threadLocalDriver.get();
//do stuff
}
@AfterMethod
public void tearDown()
{
WebDriver driver = threadLocalDriver.get();
driver.quit();
}
}
here is my enum:
public enum SupportedBrowser {
FIREFOX, CHROME; //add more as needed
public getDriver() {
if(this == SupportedBrowser.FIREFOX) {
return new RemoteDriver(hubAddress, DesiredCapabilities.firefox()); //alternatively could be new FirefoxDriver()
}
else {
return new RemoteDriver(hubAddress, DesiredCapabilities.chrome());
}
}
}
Please forgive bad code conventions, I didn't write this in an IDE (though I have used something like this and it works).
The class is run once fore each different browser. Each method has its own independent driver, making sure your test can run concurrently. It also allows each method to take its own DataProvider, in case you need a test method to run multiple times with different arguments. Also make sure that the parallel attribute is set to the "method" level in your testng.xml file.
The only issue with my code is making sure the driver quits if the test fails. Right now, this method leaves closing failed tests up to selenium grid (using -timeout). Please see my question: Sharing driver between @BeforeMethod and @AfterMethod in TestNG.
Edit: I have now added a ThreadLocal variable to the code that shares the driver throughout the thread, so you can call driver.quit() in the @AfterMethod.