Friday 26 September 2014

Selenium - Object Locators

Selenium webdriver uses 8 locators to find the elements on web page. The following are the list of object identifier or locators supported by selenium.
We have prioritized the list of locators to be used when scripting.
1. id
2. Name
3. Linktext
4. Partial Linktext
5. Tag Name
6. class name
7. Css
8. xpath
Locating an Element By ID:
The most efficient way and preferred way to locate an element on a web page is By ID. ID will be the unique on web page which can be easily identified.
IDs are the safest and fastest locator option and should always be the first choice even when there are multiple choices, It is like an Employee Number or Account which will be unique.
Example 1:
Example 2:
We can write the scripts as

Unfortunately there are many cases where an element does not have a unique id (or the ids are dynamically generated and unpredictable like GWT). In these cases we need to choose an alternative locator strategy, however if possible we should ask development team of the web application to add few ids to a page specifically for (any) automation testing.
Locating an Element By Name:
When there is no Id to use, the next worth seeing if the desired element has a name attribute. But make sure there the name cannot be unique all the times. If there are multiple names, Selenium will always perform action on the first matching element
Example:

Locating an Element By LinkText:
Finding an element with link text is very simple. But make sure, there is only one unique link on the web page. If there are multiple links with the same link text (such as repeated header and footer menu links), in such cases Selenium will perform action on the first matching element with link.
Example:

Locating an Element By Partial LinkText:
In the same way as LinkText, PartialLinkText also works in the same pattern.
User can provide partial link text to locate the element.
Example:

Locating an Element By TagName:
TagName can be used with Group elements like , Select and check-boxes / dropdowns.
below is the example code:

Locating an Element By Class Name:
There may be multiple elements with the same name, if we just use findElementByClassName,m make sure it is only one. If not the you need to extend using the classname and its sub elements.
Example:

CSS Selector:
CSS mainly used to provide style rules for the web pageIs and we can use for identifying one or more elements in the web page using css.
If you start using css selectors to identify elements, you will love the speed when compared with XPath.
We can you use css which can also run with the same speed in IE browser. CSS selector is always the best possible way to locate complex elements in the page.
Example:

XPath Selector:
XPath is designed to allow the navigation of XML documents, with the purpose of selecting individual elements, attributes, or some other part of an XML document for specific processing
There are two types of xpath
1. Native Xpath, it is like directing the xpath to go in direct way. like
Example:
html/head/body/table/tr/td
Here the advantage of specifying native path is, finding an element is very easy as we are mantion the direct path. But if there is any change in the path (if some thing has been added/removed) then that xpath will break.
2. Relative Xpath.
In relative xpath we will provide the relative path, it is like we will tell the xpath to find an element by telling the path in between.
Advantage here is, if at all there is any change in the html that works fine, until unless that particular path has changed. Finding address will be quite difficult as it need to check each and every node to find that path.
Example:
//table/tr/td

Wednesday 24 September 2014

Read background color of an element?

driver.get("http://www.google.co.in/");

String color = driver.findElement(By.name("btnK")).getCssValue("background-color");
   
System.out.println("The background color of Google search button"+color);

How to take screenshot of the page?

WebDriver driver = new FirefoxDriver();

driver.get("http://google.com/");

//Get the screenshot as file
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
  
// Copy the screenshot to your file system
FileUtils.copyFile(scrFile, new File("c:\screenshots\screenshot.png"));

Different Ways to Refresh Browser


1. Refresh command: Most commonly used and simple command for refreshing a webpage.
driver.get("https://www.google.com");

driver.navigate().refresh();
--------------------------------------------------------------------------------------------------------------------------

2. SendKeys command: Second most commonly used command for refreshing a webpage. As it is using a send keys method, we must use this on any Text box on a webpage.
driver.get("https://www.google.com");

// Here "gs_htif0" is a Seach box in the site

driver.findElement(By.id("gs_htif0")).sendKeys(Keys.F5);
-------------------------------------------------------------------------------------------------------------------------

3. Get command: This is a tricky one, as it is using another command as an argument to it. If you look carefully, it is just feeding get command with a page url.
driver.get("https://www.google.com");

driver.get(driver.getCurrentUrl());
------------------------------------------------------------------------------------------------------------------------

4. To command: This command is again using the same above concept. navigate( ).to( ) is feeding with a page url and an argument.
driver.get("https://www.google.com");

driver.navigate().to(driver.getCurrentUrl());
------------------------------------------------------------------------------------------------------------------------

5. SendKeys command: This is same SendKeys command but instead of using Key, it is using ASCII code.
driver.get("https://www.google.com");

driver.findElement(By.id("gs_htif0")).sendKeys("\uE035");

Wednesday 17 September 2014

Handle Alert popup in selenium

Steps:
  •  Get the reference of the main window
  •  Switch to Alert popup
  • As per requirement accept or dismiss alert
  • Switch back to main window
String mainWindow = driver.getWindowHandle();
Alert alert = driver.switchTo().alert(); 
alert.accept(); 
//alert.dismiss();
driver.switchTo().window(mainWindow );

Tuesday 16 September 2014

Drag and Drop element

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class Dropdrag {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.get("http://yuiblog.com/sandbox/yui/3.2.0pr1/examples/dd/groups-drag_clean.html");
        Actions act = new Actions(driver);
        WebElement source1 = driver.findElement(By.id("pt1"));
        WebElement target1 = driver.findElement(By.id("t2"));
        act.dragAndDrop(source1,target1).perform();
    }
}

Selenium Interview Questions


Caught Exception and Uncaught exception

Caught Exception:
When the programmer is not liable for error, Error come in run time, after execution.
Ex: int i =5/0;

Uncaught Exception:
When programmer is liable for error. Error comes at the time of programming.
Ex:
Thread.sleep(5000L);
---------------------------------------------------------------------------------------------------------
Difference between "Add throws declaration" and Surround with Try/Catch

Add throws declaration: If we don't want to report the error than we use this function.

Surround with Try/Catch block: If we want to report the error in selenium report than we use this function.
---------------------------------------------------------------------------------------------------------

Difference between Throws and Throw

Throws: Throws come in front of function and it tells Java that this function is capable of throwing an exception.
Ex: Add throws declaration" or Surround with Try/Catch

Throw: Throw clause is used to deliberately through an exception.
---------------------------------------------------------------------------------------------------------

Difference between final and finally

final: Stats that you cannot change the value of variable.
Ex: final int s=100; // Cannot change the value
        //s =101;  //it will give error

finally: finally is used with try/catch block. Finally stats that (finally is a block) it will executed for sure weather try block or catch block is executed or not.
Ex: try{
    //establish DB connection
    //fire query
    //get results
    //close connection
    }catch{Exception e}
    {
    //error
    System.out.println("error");
    }finally{
    //close the connection if established
    System.out.println("is finally");
    }
---------------------------------------------------------------------------------------------------------
Difference between Error and Exception:
Error: Out of memory error, ex: Assertion error thrown, when running the eclipse sometimes when run big program when error comes eclipse gone out of memory error.
Exception: run time exception, null pointer exception; divide by zero exception, array index out of bond etc.
---------------------------------------------------------------------------------------------------------
String to Integer Conversion:
String x = 100;
int 1 = Integer.parseInt (x);

int is the primitive data type but Integer is an in build  class just like a String class which represent int.
---------------------------------------------------------------------------------------------------------
Integer to String Conversion:
String z = String.valueof(i);
---------------------------------------------------------------------------------------------------------
String to Boolean conversion:
boolean b = Boolean.valueof("true");
https://mail.google.com/mail/u/0/images/cleardot.gif
---------------------------------------------------------------------------------------------------------
Collection API: Array List and Hash table are collection API.

ArrayList is similar to Array but it is not an array, it is inbuilt class and it is dynamically growing in size.

Ex: It is used where we need to read/get bulk data from site, get data from popup etc.
ArrayList <String> list = new ArrayList <String>();
        list.add("A");
        list.add("B");
        list.add("C");
        System.out.println(list.size());
for(int i =0;i<list.size();i++)
        {
            System.out.println(list.get(i));
        }

---------------------------------------------------------------------------------------------------------
Hah table and array list both are dynamically growing data structure. whereas Array List grow with index and Hash table grows with Kay and Value pair.
---------------------------------------------------------------------------------------------------------
HashTable: Hashtable is inbuilt class we can create object of the class. Hashtable contains key value pair (key and value). Key should be unique and corresponding to each key there should be a value.
Ex: We used Hash table to store test data.

Hashtable <String, String> table = new Hashtable <String, String>();
        table.put("Name", "Sunil");
        table.put("Company", "InfoBeans");
        table.put("Place","Indore");
        System.out.println("------------ Hash Table ----------");
        System.out.println(table.get("Name"));

Selenium Script for MySQL database connectivity

Prerequisite:

Download - mysql-connector-java-5.1.25-bin.jar and add it to your project

Sample Script:
import java.sql.*;
import javax.sql.*;

public class dbconnection{
 
public static void main(String args[]){
   String username;
   String dbUrl = "jdbc:mysql://localhost:3306/test";  //This URL is based on your IP address
   String username="username"; //Default username is root
   String password="password"; //Default password is root
   String dbClass = "com.mysql.jdbc.Driver";
   String query = "Select username from users where user_id = 1;";
  try {
      Class.forName(dbClass);
      Connection con = DriverManager.getConnection (dbUrl,username,password);
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery(query);

      while (rs.next()){
        dbtime = rs.getString(1);
        System.out.println(username);
       } //end while

  con.close();
  } //end try

catch(ClassNotFoundException e) {
e.printStackTrace();
}

catch(SQLException e) {
e.printStackTrace();
}

}  //end main

}  //end class

Open browser (IE, Firefox, Chrome) dynamically

public void openBrowser(String browserType){

        if(browserType.equalsIgnoreCase("Mozilla")){
            driver = new FirefoxDriver();

        }else if(browserType.equalsIgnoreCase("IE")){

            System.setProperty("webdriver.ie.driver",System.getProperty("user.dir")+"\\driver\\IEDriver.exe");

            driver = new InternetExplorerDriver();
        }else if(browserType.equalsIgnoreCase("Chrome")){

            System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\driver\\chromedriver.exe");
  
            ChromeOptions options = new ChromeOptions();
            driver = new ChromeDriver();
        }else{
            System.out.println("Please enter correct browser name");
        }

        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.manage().window().maximize();
       
    }