23
Jul

Driver utilities for Selenium

package SeleniumTestUtilities;

import java.net.MalformedURLException;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.Test;

public final class WebDriverUtilities {
	
	private WebDriver driver = null;
	private RemoteWebDriver remoteWebDriver = null;
	
	public ChromeOptions setChromeCapabilities() {
		System.setProperty("webdriver.chrome.driver", "c:/selenium/chromedriver.exe");
		
		DesiredCapabilities cap = DesiredCapabilities.chrome();
		cap.setCapability("chrome.binary", "c:/selenium/chromedriver.exe");
		cap.setCapability("platformName", "WIN10");
		ChromeOptions options = new ChromeOptions();
		
		options.merge(cap);
		return options;
	}
	
	public WebDriver getWebDriver(String browser) {
		if(browser.equalsIgnoreCase("chrome")) {
			driver = new ChromeDriver(setChromeCapabilities());
			return driver;
		}else if(browser.equalsIgnoreCase("firefox")) {
			driver = new FirefoxDriver();
			return driver;
		}
		return driver;
	}
	
	public RemoteWebDriver getRemoteDriver() {
		if(System.getProperty("gridExecution") == "yes") {
			try {
				remoteWebDriver = new RemoteWebDriver(new URL("http://10.174.88.159:4444/wd/hub"), setChromeCapabilities());
			}catch(MalformedURLException e) {
				e.printStackTrace();
			}
			
			return remoteWebDriver;
		}
	}
	
	@Test(enabled=false)
	public void myBrowser() {
		driver = getWebDriver("chrome");
		driver.get("http://google.com");
		driver.quit();
	}

	@Test(enabled=true)
	public void myRemoteWebDriver() {
		remoteWebDriver = getRemoteDriver();
		remoteWebDriver.get("http://google.co.in");
		remoteWebDriver.quit();
	}
}