06
Feb

BasePage design to accommodate dynamic environments and browsers

Sample BasePage and test classes with an Automation framework:
======================================================================

#1. Base class
================

import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;

public class BasePage {

	protected WebDriver webdriver;

	@BeforeSuite
	public void setUp() {
		System.setProperty("webdriver.chrome.driver", "c:\\Browserdrivers_Selenium\\chromedriver.exe");
		String seleniumUrl = System.getProperty("selenium.url");
		System.setProperty("webdriver.chrome.driver", "c:\\Browserdrivers_Selenium\\chromedriver.exe");

		if (seleniumUrl == null) {
			seleniumUrl = "https://www.amazon.in";
		}

		webdriver = setupWebDriver();
		webdriver.get(seleniumUrl);
	}

	@AfterSuite
	public void tearDown() {
		webdriver.quit();
	}

	private WebDriver setupWebDriver() {
		final String driverProperty = System.getProperty("selenium.driver");
		final Driver driver;
		if (driverProperty == null) {
			driver = Driver.CHROME;
		} else {
			driver = Driver.valueOf(driverProperty);
		}

		return driver.start();
	}

	protected enum Driver {
		FIREFOX, HTML_UNIT, CHROME, EDGE, INTERNET_EXPLORER, SAFARI;

		WebDriver start() {
			switch (this) {
			case FIREFOX:
				return new FirefoxDriver();
			case HTML_UNIT:
				return new HtmlUnitDriver();
			case CHROME:
				return new ChromeDriver();
			case EDGE:
				return new EdgeDriver();
			case INTERNET_EXPLORER:
				return new InternetExplorerDriver();
			case SAFARI:
				return new SafariDriver();
			default:
				throw new AssertionError();
			}
		}
	}

}


Step 2:  Design your tests
===========================

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;

public class BasePagetest extends BasePage {

	private WebDriver driver;

	@Test
	public void myFunction() {

		driver.findElement(By.name("q")).sendKeys("Hello");
	}

}


Step 3:  configure your tests with TestNG.xml suite
==========================================================

Run your tests from testng.xml suite with following parameters as "vmarguments"
-Dselenium.driver=CHROME
-Dselenium.url=http://www.google.co.in



advantages:

User can control different browsers and different URLs tested without touching code or property files.