ISTQB Certified Software Test Engineer

Thursday, March 29, 2012

Running a Selenium Script Parallelly using Web Driver

If we want to run a Selenium Script across multiple machines parallelly we are using Selenium Grid.
Using Selenium web driver we can achieve this parallel execution with the help of Remote Web driver class and starting Standalone jar on the remote machine(remote machine may be your local some times).
But with this approach you can run the script in multiple browsers in the same
machine.
The prerequisites to implement this using web driver are
1.Browsers to be installed in the machine
2.Standalone Selenium Server jar has to be started.
Here is the sample code


import static org.junit.Assert.assertTrue;

import java.net.MalformedURLException;
import java.net.URL;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class GoogleTest {

public static WebDriver driver;
@BeforeClass
public static void main(String args[]) throws Exception{

DesiredCapabilities browsers[] ={DesiredCapabilities.firefox(),DesiredCapabilities.internetExplorer()};

for(DesiredCapabilities capabilities :browsers){

System.out.println("Executing Google Test in"+capabilities.getBrowserName());
driver =new RemoteWebDriver(new URL("http://127.0.0.1:4444/wd/hub"), capabilities);

driver.get("http://google.com");
driver.get("http://www.google.com");
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("Cheese!");
element.submit();
System.out.println("Page title is: " + driver.getTitle());
assertTrue(driver.getTitle().contains("cheese!"));


}

}
}