Creating new instance of firefox driver
WebDriver driver = new FirefoxDriver();
Creating new instance of Chrome driver
System.setProperty("webdriver.chrome.driver","system.getProperty(user.dir)+
/drivers/Chromedriver.exe")
WebDriver driver = new ChromeDriver();
Chromium Driver
ChromeOptions options = new ChromeOptions();
options.setBinary("path/to/chromium"); // e.g., "C:/chromium/chrome.exe"
WebDriver driver = new ChromeDriver(options);
Creating new instance of IE driver
System.setProperty("webdriver.ie.driver", "D:\\....\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
Command to open URL in browser
driver.get("http://www.---.com");
Clicking on an element
driver.findElement(By.xpath(" ")).click();
Storing text of targeted element in a variable
String var = driver.findElement(By.id("")).getText();
Typing text in text box
driver.findElement(By.name(" ")).sendKeys("mylastname");
Getting the value from text box
driver.findElement(By.name(" ")).getAttribute("value");
Implicit wait
driver.manage().timeouts().implicityWait(Duration.ofSeconds(10));
Explicit wait
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath(""), "Download complete");
alertIsPresent, elementToBeClickable, elementToBeSelected, visibilityof ElementLocated, presenceOfElementLocated
Fluent wait
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTImeOut(Duation.ofSeconds(10)) .pollingEvery(Duation.ofSeconds(10)) .ignoring(NoSuchElementException.class);
Get page title
driver.getTitle();
Get Current Page URL
driver.getCurrentUrl();
Get domain using java script executor
JavaScriptExecutor executor = (JavaScriptExecutor) driver;
String currentURL = (String)executor.executeScript("return document.domain");
Generate alert using java script executor
JavaScriptExecutor executor = (JavaScriptExecutor) driver;
executor.executScript("alert("Test Case Execution is started now..");");
Selecting or Deselecting value from drop down
Select drpdwn = new Select(driver.findElement(By.id(" ")));
drpdwn.(de)selectByVisibleText("Audi");
drpdwn.(de)selectByIndex(1);
drpdwn.(de)selelctByValue("Italy");
Removing all selections from listbox
Select listbox = new Select(driver.findElement(By.xpath(" "))); listbox.deselectAll();
Checking whether a select box is multiselect
boolean value = listbox.isMultiple();
Retrieving all values from dropdown
List<WebElement> options = select.getOptions();
Navigate to backward or forward
driver.navigate().to(" ");
driver.navigate().back();
driver.navigate().forward();
Refresh the page
driver.navigate.refresh()
Verify whether a element present
Boolean isElementPresenet = driver.findElements(By.xpath(" ")).size()!=0;
Capturing screenshot
File screenshot = ((TakesScreenShot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(sceenshot, newFile(System.getProperty(user.dir)/ScreenShots);
Generating mouse hover event Actions
actions = new Actions(driver);
WebElement menu = driver.findElement(By.xpath(" "));
actions.moveToElement(menu).build().perform();
Handling multiple windows file
String pWindow = (String)AllWindows.toArray()[0];
String cWindow = (String)AllWindows.toArray()[1];
driver.swithTo().window(cWindow);
String parent=driver.getWindowHandle(); // to get the parent window name
// Now iterate using Iterator
Iterator<String> I1= allWindows.iterator();
while(I1.hasNext())
{
String child_window=I1.next();
if(!parent.equals(child_window))
{
driver.switchTo().window(child_window);
System.out.println(driver.switchTo().window(child_window).getTitle());
driver.close();
}
}
Check whether an element is enabled or disabled
Assertions with TestNG framework
Assert.assertEquals(actual, expected) - to assert actual and expected values are equal
Assert.assertNotEquals(actual, expected) - to assert not equal values
Assert.assertTrue(condition) - works for boolean value true assertion
Assert.assertFalse(condition) - works for boolean value false assertion
Submitting a form
driver.findElement(By.xpath(" ")).submit();
Handling alerts String
myalert = driver.switchTo().alert().getText();
driver.switchTo().alert().accpet();
driver.switchTo().alert().dismiss();
driver.switchTo().alert().sendKeys(" ");
Handling drag and drop
Actions ac = new Actions();
ac.dragAndDrop(driver.findElement(By.id("draggable"), driver.findElement(By.id("droppable")))).
build.perform();
Handling the frames
driver.switchTo().frame("frameid/name/index"); //to enter the frame driver.switchTo().defaultContent(); //to exit the frame
Calendar popups
driver.findElement(By.id("calendar_icon 1")).click();
driver.findElement(By.xpath("//div[@id='CalendarControl']/table/tbody[tr[td[text()='Octoer 2012']]]] /descendant::a[text()='5'])).click();
Context click (Right Click)
WebElement parentMenu = driver.findElement(By.linkText("Srinivas"));
Actions act = new Actions(driver);
act.contextClick(parentMenu).build().perform();
act.sendKeys(Keys.ARROW_DOWN).build().perform();
Thread.sleep(1000);
act.sendKeys(Keys.ENTER).build().perform();
Auto IT
WinWaitActivate("Authentication Required")
Send("admin") Send("{TAB} admin {TAB} {ENTER}")
Save the file as 'Authentication.exe'
Calling .exe file in selenium
Process P = Runtime.getRuntime().exec("D:\\....\\Authentication.exe");
File Download using RobotClass
Robot robot = new Robot();
robot.KeyPress(KeyEvent.VK_ALT);
robot.KeyPress(KeyEvent.VK_S);
robot.KeyRelease(KeyEvent.VK_ALT);
robot.KeyRelease(KeyEvent.VK_S);
Thread.sleep(2000);
robot.KeyPress(KeyEvent.VK_ENTER);
robot.KeyRelease(KeyEvent.VK_ENTER);
Thread.sleep(2000);
File upload using webDriver
WebElement fileInput = driver.findElement(By.xpath("//input[@type='file'][@name='photfile']")); fileInput.sendKeys("D:\\.....\\Desert.jpg"); Thread.sleep(2000);
Scrolling
Actions ac = new Actions(driver); ac.KeyDown(Keys.CONTROL).sendKeys(Keys.HOME).build().perform(); ac.KeyDown(Keys.CONTROL).sendKeys(Keys.END).build().perform(); (OR) WebElement element = driver.findElement(By.xpath("scroll bar locator")); ac.moveToElement(element).clickANDHold().moveByOffset(x,y).release().perform();
Fluent Wait
FluentWait <WebDriver> wait = new FluentWait<WebDriver>(driver) .withTImeOut(30,SECONDS); .pollingEvery(5,SECONDS); .ignoring(NoSuchElementException.class)
Sample X paths
//input[contains[@name,'Name')]
//input[starts_with(@name, txt')]
//input[@name = 'txtUserName']
//table[@id = 'Table_o1']/tbody/tr/td[2]/input //a[contains(text(), "RRR")]
//h1[normalize-space(text()) = 'Dashboard']
Clicking on web element WebElement element = driver.findElement(By.id("id of webelement")); JavaScriptExecutor js = (JavaScriptExecutor) driver; js.executeScript("arguments[0].click();", element);
Typing in text box js.execteScript("document.getElementById('id of the eleement').value='test data';"); Scrolling down js.executeScript("arguments[0].scrollIntoView(true);", element);
Scroll to an element
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollIntoView();", element);
Scroll to bottom of the page
((JavascriptExecutor) driver)
.executeScript("window.scrollTo(0, document.body.scrollHeight)");
Scroll to coordinates
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,500)");
DB Connection
Connection con = DriverManager.getConnection(“url”,”name’,”password”);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(“”);
While(rs.next())
{
String empID = rs.getString(1);
String ename = rs.getString(2);
S.O.S(empID + “ “+ename);
}
Exceptions
Throwable -> Exception , Error
Checked Exceptions(Compile time exceptions) –
IOException, SQLException, ClassNotFoundException, FileNotFoundException
Unchecked exceptions(Run time exceptions) –
ArithmeticException, NullPointer Exception, ArrayIndexOOB Exception
Try, Catch, Throw, Throws, finally
Error -> StackOverflowError, OutofMemoryError, VirtualMachineError
Selenium Exceptions
NoSuchElementException
NoSuchFrameException
NoSuchWindowException
NoAlertPresentException
SessionNotFoundException
StaleElementReferenceException
ElementNotVisibleException
Shadow - DOM - Part of the DOM inside an element
<my-button>
#shadow-root (open)
<button id="shadowBtn">Click Me</button>
</my-button>
normal DOM- driver.findElement(By.id("shadowBtn")).click();
Shadow DOM
// 1. Find the shadow host
WebElement shadowHost = driver.findElement(By.cssSelector("my-button"));
// 2. Use JavaScript to access the shadow root
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement shadowRoot = (WebElement) js.executeScript("return arguments[0].shadowRoot", shadowHost);
// 3. Find and click the button inside the shadow root
WebElement shadowButton = shadowRoot.findElement(By.cssSelector("#shadowBtn"));
shadowButton.click();
Reading excel file
FileInputStream excel = new FileInputStream(d:\....);
Workbook wb = new Workbook(excel);
Sheet sh = wb.getSheet(0);
Int rows = sh.getLastRowNum();
Int columns = sh.getRow(0).getLastCellNum();
for(int i=0;i<=rows; i++)
{ for(int j=1;j<=columns, j++)
{ String cellData = sh.getRow(i).getCell(j).getStringCellValue();
}
Report Utils
Org.testng.ITestListener;
Org.testng.ITestContext;
Org.testng.ITestResult;
public class Listner implements ITestListener, ITestContext, ITestResult;
public void onStart(ITestContext arg0)
{
Reporter.log(“About to start execution” +arg0.getName(), true)
}
public void onFinish(ITestContext arg0)
{
Reporter.log(“Execution has finished” +arg0.getName(), true)
}
public void onTestFailure(ITestResult arg0)
{
Reporter.log(“TestName” +arg0.getTestName(), true);
}
public void onTestSkipped(ITestResult arg0)
{
printTestResults(arg0); }
public void onTestStart(ITestResult arg0)
{ }
public void onTestSuccess(ITestResult arg0)
{
printTestResults(arg0)
}
Selenium Grid (Parallel testing)
java -jar selenium-server-standalone-2.54.0.jar -role hub http://localhost:4444/grid/console java -jar selenium-server-standalone-2.54.0.jar -role node -hub http://localhost:4444/grid/register -port 5556
import java.net.MalformedURLException; import java.net.URL; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver;
pubic class Grid
{
public static void main(String[] args) throws Exception {
DesiredCapabilities caps = null;
if(browserType.equals(“firefox”)
{
Caps = DesiredCapabilities.firefox();
****caps.setBrowserName(“firefox”); caps.setVersion("50"); caps.setPlatform(Platform.WINDOWS);
}
else
{
Caps = DesiredCapabilities.internetExplorer ();
****caps.setBrowserName(“iexplore”); caps.setVersion("50"); caps.setPlatform(Platform.WINDOWS);
}
URL urlHub=null;
try
{
urlHub = new URL(" http://localhost:4444/wd/hub");
}
catch(MalformedURLException e)
{
e.printStackTrance();
}
RemoteWebDriver driver = new RemoteWebDriver(urlHub, caps);
driver.navigate().to(" ");
Thread.sleep(3000);
System.out.println(driver.getTitle());
driver.quit();
}
TestNG.xml for Serial and Parallel execution
<suite name=”Grid Sample Test” thread-count=2> //Serial exection
<suite name=”Grid Sample Test” parallel=”tests” thread-count=2> //parallel execution
<test name = “Grid serial(parallel) execution with browser chrome>
<parameter name = “browserType” value=”Chrome”>
<classes>
<class name = “GridExample>
<classes>
<test>
<test name = “Grid serial(parallel) execution with browser edge>
<parameter name = “browserType” value=”Edge”>
<classes>
<class name = “GridExample>
<classes>
<test>
Grouprun.xml
<suite name = “GroupRun”>
<test name = “GroupRun”>
<groups>
<run>
<include name=”Regression”>
<exclude name=”smoke”>
</run>
</groups>
WebDriver extends Search context
Remote WebDriver implements WebDriver, TakesScreenShot, JavaScriptExecutor,
Chrome, IE, Firefox drivers extends RemoteWebDriver
org.openqa.selenium.By
com.pearson.adam.pages
--Loginpage.java
--Homepage.java
--DashboardPage.java
--StudentSearchPage.java
--StudentDetailsPage.java
com.pearson.adam.testscripts
--Login_TC1.java
--StudentSearch_TC2.java
TestData
TestReports
pom.xml
TestNG.xml
public class GoogleHomePage {
private WebDriver driver;
public GoogleHomePage( WebDriver driver ) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
@FindBy(how = How.NAME, using = "q")
WebElement searchBox;
@FindBy(how = How.NAME, using = "btnK")
WebElement submit;
public void search()
{
searchBox.sendKeys("TestGrid");
}
public void submit()
{
submit.click();
}
}
Selenium RC
Start selenium server C:\cd SeleniumRC (Path of the jar file) C:\cd SeleniumRC>Seleniumserver>java -jar selenium-server.jar
Changing the port number
java -jar selenium-server.jar-port 1212 To shut down server: Ctrl+C
RC Basic program
import org.openqa.selenium.server.*;
import com.thoughtworks.selenium.*;
public class basicRCprog
{
public static void main(String[] args)throws Exception
{
RemoteControlConfiguration rc = new RemoteControlConfiguration();
rc.setPort(5555);
SelenimServer objserver = new SeleniumServer();
Selenium objselenium = new DefaultSelenium("localhost", 4444, "*firefox","http://...."); objserver.start();
objselenium.start();
objselenium.windowmaximize();
objselenium.open("http://...");
objselenium.type("txtUserName", "selenium");
objselenium.type("txtPassword", "selenium");
objselenium.click("Submit");
objSelenium.waitForPageToLoad("2000");
objselenium.click("link=Logout");
objselenium.stop();
objserver.stop(); } }
Dependencies - BDD
RestAssured
json-schema-validator
json-path
xml-path
java-hamcrest
**hamcrest-core(deprecated)
**hamcrest-library(deprecated)
Dependencies - Java and TestNG
RestAssured
Json-simple
apche poi
TestNG
BDD Cucumber framework
Step 1 – Setup & Configuration
1. JDK
2. Eclipse/Intellij
3. Cucumber plugin & Natural plugin in Eclipse through Market
4. Setup Environment Variables
a. Java Home
b. Maven Home
c. M2 Home
Step 2 – Create Maven Project and update pom.xml with below dependencies
a. Cucumber -core
b. Cucumber -html
c. Cobertura code coverage
d. Cucumber -java
e. Cucumber -junit
f. Cucumber -jvm-deps
g. Cucunber -reporting
h. Harmcrest -core
i. Gherkin
j. Junit
k. Selenium -java
Step 3 – Create Folder Structure
Project Name -> Features (Folder) -> pageObjects (Package) -> StepDefinitions (Package)->
Utilities (Package) -> Drivers -> Target (Reports) -> pom.xml
Folder – non java class files (at project level), Package – java class files
Step 4 – Copy Drivers into “Drivers” folder
Step 5 – Automating Login test case
· Create a login.feature under Feature files folder
· Create Page object class LoginPage.java under PageObjects package
· Create loginSteps.java under stepDefinitions package and implement required methods
· Create TestRunner.java under myRunner package.
C