0% found this document useful (0 votes)
146 views

Selenium IMportant Notes

This document provides examples of how to perform various automation tasks using Selenium including: 1) Checking if all links on a webpage are working by making HTTP requests and validating response codes 2) Using the Page Object Model pattern with PageFactory to initialize page objects 3) Performing headless browser testing using HtmlUnitDriver
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
146 views

Selenium IMportant Notes

This document provides examples of how to perform various automation tasks using Selenium including: 1) Checking if all links on a webpage are working by making HTTP requests and validating response codes 2) Using the Page Object Model pattern with PageFactory to initialize page objects 3) Performing headless browser testing using HtmlUnitDriver
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

1)Check if all links in a webpage are working.

List<WebElement> testlink_List=driver.findElements(By.locator(“”));
For(WebElement testlink : testlink_List){
URL link=new URL(testlink);
HttpURLConnection url=(HttpURLConnection)link.openConnection();
int code= url.getResponseCode();
if(code >=400)
System.out.println(“Links are broken”);
else
System.out.println(“Links are proper”);
}

Note :
In General 2xx :proper, 4xx and 5xx are errors.
400 :The request is invalid
401 :Unauthorized error
404 :The requested resource was not found.
500 :Internal Server Error

2) How to use Pagefactory and POM model ?

public class PageObjctClass {


@FindBy(id="nav-your-amazon")
@CacheLookup
public WebElement YourAmazonIn;
}

public class ToTestPom {

@Test
public void Amazon() {
System.setProperty("webdriver.gecko.driver", "D:\\Study
materials\\Setups\\geckodriver.exe");
FirefoxDriver driver=new FirefoxDriver();
driver.get("https://www.amazon.in/");
PageObjctClass page=PageFactory.initElements(driver, PageObjctClass.class);
WebDriverWait wait=new WebDriverWait(driver, 30);
page.YourAmazonIn.click();
}
}

3) What is Headless browser testing and how is it done?

Headless browser is a term used to define browser simulation programs which do not
have a GUI. These programs behave just like a browser but don’t show any GUI.
Selenium supports headless testing using its class called HtmlUnitDriver.

HtmlUnitDriver unitDriver = new HtmlUnitDriver(); [Download htmlunit-driver in order


to use this]

Once you have the Html unit driver you can just use it as a regular WebDriver.
4) How to handle HTTP Proxy Authentication ?

driver.get("http://UserName:[email protected]");

5) How to handle Windows file upload pop up using AutoIT ?

ControlFocus("Open", "", "Edit1")

ControlSetText("Open", "", "Edit1", "C:\Users\Dheemanth\Desktop\index.html")

ControlClick("Open", "", "Button1")

Save as .au3 format. Then Right click on the file and click Compile script to
generate .exe file.

In Eclipse, after clicking on the file upload button, use Runtime.getRuntime().exec()


and pass the generated .exe file path as argument.

As an alternate, Directly pass the File path to the Upload button via SendKeys().

6) Explain Robot class events in Selenium.

Robot robot=new Robot();

robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); // press left click


robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); // release left click
robot.keyPress(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_TAB);
robot.mouseMove(630, 420)

7) Data driver framework


package com.prasanna.excellibrary;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class ExcelLibrary {


Sheet s;
Workbook wb;
Row r;
Cell c;
DataFormatter formatter=new DataFormatter();
public String getExcelData(String sheetname,int i, int j) {
String dataText=null;
try {
FileInputStream fis=new
FileInputStream("//media//disk1//ESyncSelenium//login.xls");
wb=WorkbookFactory.create(fis);
s=wb.getSheet(sheetname);
r=s.getRow(i);
c=r.getCell(j);
dataText = formatter.formatCellValue(c);

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dataText;
}

public boolean setCellData(String sheetName, int colNumber, int rowNum, String


value)
{
try
{
s = wb.getSheet(sheetName);
r = s.getRow(rowNum);
if(r==null)
r = s.createRow(rowNum);

c = r.getCell(colNumber);
if(c == null)
c = r.createCell(colNumber);

c.setCellValue(value);

FileOutputStream fos = new FileOutputStream("//media//disk1//ESyncSelenium//login.xls");


wb.write(fos);
fos.close();
}
catch (Exception ex)
{
ex.printStackTrace();
return false;
}
return true;
}

8) Selenium GRID

1. Download “Selenium Standalone Server” from


“http://www.seleniumhq.org/download/” on all 3 machines
2. Goto machine 1 and open command prompt.
3. Navigate to location where jar is located.
4. Start Hub by command:  java -jar selenium-server-standalone-2.48.2.jar -role hub
5. Open browser and navigate to http://localhost:4444/grid/console and verify hub is
started by checking below image.

6. Goto machine 2 and open command prompt


7. Navigate to location where jar is located.
8. Start Node by command: java -Dwebdriver.chrome.driver={path to
chromedriver.exe}-jar selenium-server-standalone-2.48.2.jar -role webdriver -hub
-port 5560 -browser browserName=chrome,maxInstances=2,maxSession=2
9. Goto machine 1 and in browser navigate to http://localhost:4444/grid/console and
verify node is started by checking below image.

10.Goto machine 3 and open command prompt.


11.Navigate to location where jar is located.
12.Start Node by command: java -jar selenium-server-standalone-2.48.2.jar -role
webdriver -hub -port 5557 -browser
browserName=firefox,maxInstances=5,maxSession=2
13.Goto machine 1 and in browser navigate to http://localhost:4444/grid/console and
verify node is started by checking below
image. 

14.Nodes can be opened for various settings like browser, platform, version.
15.Now Selenium Hub and Nodes are created, lets make some @Test and execute
them.
16.Make Project on any machine, my project structure as below:

17.Source code for files are given below.


18.Execute testng.xml and execution will start parallely on both machines.

testng.xml

<?xml version="1.0" encoding="UTF-8"?>


<suite name="Parallel test suite" parallel="classes" thread-count="2">
    <test name="Regression 1">
        <parameter name="myBrowser" value="firefox"/>
        <classes>
            <class name="myPackage.TestParallel" />
            <class name="myPackage.TestParallel" />
        </classes>
    </test>
    <test name="Regression 2">
        <parameter name="myBrowser" value="chrome"/>
        <classes>
            <class name="myPackage.TestParallel" />
            <class name="myPackage.TestParallel" />
        </classes>
    </test>
 
</suite>
BaseClass.java

package myPackage;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
 
public class BaseClass {
 
    //ThreadLocal will keep local copy of driver
    public static ThreadLocal<RemoteWebDriver> dr = new
ThreadLocal<RemoteWebDriver>();
 
    @BeforeTest
    //Parameter will get browser from testng.xml on which browser test to run
    @Parameters("myBrowser")
    public void beforeClass(String myBrowser) throws MalformedURLException{
 
        RemoteWebDriver driver = null;
 
        if(myBrowser.equals("chrome")){
            DesiredCapabilities capability = new DesiredCapabilities().chrome();
            capability.setBrowserName("chrome");
            capability.setPlatform(Platform.WINDOWS);
            driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),
capability);
        }
        else if(myBrowser.equals("firefox")){
            DesiredCapabilities capability = new DesiredCapabilities().firefox();
            capability.setBrowserName("firefox");
            capability.setPlatform(Platform.WINDOWS);
            driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),
capability);
        }
 
        //setting webdriver
        setWebDriver(driver);
 
        getDriver().manage().window().maximize();
        getDriver().manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 
    }
 
    public WebDriver getDriver() {
        return dr.get();
    }
 
    public void setWebDriver(RemoteWebDriver driver) {
        dr.set(driver);
    }
 
    @AfterClass
    public void afterClass(){
        getDriver().quit();
        dr.set(null);
 
    }
 
}

TestParallel.java

package myPackage;
 
import java.net.MalformedURLException;
import java.net.URL;
 
import org.openqa.selenium.By;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
 
public class TestParallel extends BaseClass {
 
    @Test
    public void test_01() throws InterruptedException, MalformedURLException{
        try{
            getDriver().get("http://www.w3schools.com/");
             getDriver().findElement(By.xpath("html/body/div[2]/div/a[4]")).click();
 
            //Wait intentially added to show parallelism execution
            Thread.sleep(10000);
             getDriver().findElement(By.xpath("//*[@id='gsc-i-
id1']")).sendKeys("test");
            Thread.sleep(5000);
 
        }
        catch(Exception e){
            System.out.println(e);
        }
    }
}

9) Starts-with and innerHTML


//a[starts-with(@id,'nav') and contains(.,'Your')]

10) DataProvider
public class DataProviderTest {
 
private static WebDriver driver;
 
  @DataProvider(name = "Authentication")
 
  public static Object[][] credentials() {
 
        return new Object[][] { { "testuser_1", "Test@123" }, { "testuser_1", "Test@123" }};
 
  }
 
  // Here we are calling the Data Provider object with its Name
 
  @Test(dataProvider = "Authentication")
 
  public void test(String sUsername, String sPassword) {
 
  driver = new FirefoxDriver();
 
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 
      driver.get("http://www.store.demoqa.com");
 
      driver.findElement(By.xpath(".//*[@id='account']/a")).click();
 
      driver.findElement(By.id("log")).sendKeys(sUsername);
 
      driver.findElement(By.id("pwd")).sendKeys(sPassword);
 
      driver.findElement(By.id("login")).click();
 
      driver.findElement(By.xpath(".//*[@id='account_logout']/a")).click();
 
      driver.quit();
 
  }
 
}

You might also like