Tuesday 19 June 2012

Running test case in multiple browsers parallely in WebDriver

we can run test script in different browsers parallely using web driver. Write one test script and configure in testng xml to run that test case in IE, firefox and chrome parallely.





package com.web;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class ParallelRunning {

private WebDriver driver=null;
@BeforeTest
@Parameters ({"BROWSER"})
public void setup(String BROWSER){
System.out.println("Browser: " + BROWSER);

if (BROWSER.equals("FF")) {
System.out.println("FF is selected");
driver = new FirefoxDriver();
} else if (BROWSER.equals("IE")) {
System.out.println("IE is selected");
driver = new InternetExplorerDriver();
} else if (BROWSER.equals("HU")) {
System.out.println("HU is selected");
driver = new HtmlUnitDriver();
} else if (BROWSER.equals("CH")){
System.out.println("Google chrome is selected");
driver = new ChromeDriver();
}
}

@Test
public void testParallel()throws Exception{

driver.get("http://www.google.com");
Thread.sleep(5000);
WebElement search = driver.findElement(By.name("q"));
search.sendKeys("automation blog by niraj");
search.submit();
Thread.sleep(5000);
Assert.assertTrue(driver.getPageSource().contains("automationtricks.blogspot.com"));
driver.findElement(By.xpath("//a[contains(@href,'automationtricks.blogspot.com')]")).click();
Thread.sleep(15000);
Assert.assertTrue(driver.getPageSource().contains("working as Associate Manager @CSC"));
driver.quit();

}
}



In the above sample program BROWSER is a variable which value would be passed from TestNG.xml and TestNG.xml will run the test multiple time each time BROWSER value would be set with different browser name and test will check the BROWSER value and decide which browser test will run.

TestNG.xml