Wednesday 28 February 2018

Different Locators in Selenium

Locators is most important part of selenium automation because based on this we are going to find element on tha pgae. So, it locators failed to find element then our script will fail.

sometime locate accurate GUI element on page is very difficult task. Hence, Selenium provide many type of locators and we can use to find GUI element on page.

Below are different type of locators available in selenium.

  • ID
  • Name
  • Link Text
  • DOM
  • CSS Selector
  • Xpath

Locating By ID:

This locator technique is most common way to find element. Please see below image. we can find Google search text box with this.



Syntax:

driver.findElement(By.id("lst-ib"));


Locating By Name:

Locating by Name is same as Locating By ID just we have to use 'Name' attribute of tag instead of 'ID'.




Syntax:

driver.findElement(By.name("q"));



Locating By Link Text:

This technique is used only for finding link element on the page. It can not be used for text area, button or other type of element.





Syntax:

driver.findElement(By.linkText("Selenium - Web Browser Automation"));



Locating By CSS Selector:

CSS Selector is patterns used to find an element with combination of tag, id, class, and attributes. Locating by CSS Selector is more complicated than the other methods. It is very popular when element has no id. we can find element using tag and class.

1. Tag and ID



Syntax:

driver.findElement(By.cssSelector("input#lst-ib"));

# sign use for indicate ID.

2. Tag and Class



Syntax:

driver.findElement(By.cssSelector("input.gsfi"));

. sign use for indicate Class.

3. Tag and Attribute


Syntax:

driver.findElement(By.cssSelector("input[name=q]"));

4. Tag, Class and Attribute


Syntax:

driver.findElement(By.cssSelector("input.gsfi[name=q]"));


Locating By DOM:

The Document Object Model (DOM), is the way in which HTML elements are structured. Selenium is able to use the DOM in accessing page elements. We can use ID, Name for locating element with DOM

1. ID



Syntax:

document.getElementById("lst-ib");

2. Name


Syntax:

document.getElementsByName("q");

If there is multiple elements with same name then selenium will locate first element. If we want to locate second element the we have to use index. Please see below syntax.

document.getElementsByName("q")[2];


Locating By XPath:

Xpath is my favorite locators among all. 
Xpath is used XML for locating elements. Xpath is most common and widely used for locating elements. 



Syntax:

driver.findElement(By.xpath("//input[@id = 'lst-ib']"));

We can use different locators technique simultaneously in one locators.
For ex. If we want to find button which has id = abc and value = xyz then we can do with Xpath.

driver.findElement(By.xpath("//input[(@id = 'abc') and (@value = 'xyz')]"));

You can find xpath of any element with chrome browser easily. Follow below steps for find xpath.

1. Righ click on that element.
2. Click on inspect element
3. Right click on highlighted part
4. Go to Copy Option
5. Click on Copy Xpath and paste it to Notepad




How to Highlight Element in Selenium

When we click on any element in automation script then sometimes script is so fast that we can not recognize that which element is clicked.

So, we can do one thing that before click on any element we can highlight that element then click on that element. So, that we can recognize that which element is clicked.

We can not directly highlight element using selenium. We need to use Java script for highlight that element. If we want to execute java script then selenium driver directly can not execute java script. We have to use 'JavascriptExecutor' for execute java script with web driver.

I have created two function one for only highlight element and second one is for highlight element and lick on that element.

First function actually works like blinking on that element.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public void mHighlightElement(WebDriver driver, WebElement vElement)
    {     
     try
     {
      //Creating JavaScriptExecuter Interface
      JavascriptExecutor js = (JavascriptExecutor)driver;      
      for (int i=0; i<3; i++)
      {       
              js.executeScript("arguments[0].style.border='4px groove blue'", vElement);
              Thread.sleep(1000); // wait for see blinking
              js.executeScript("arguments[0].style.border=''", vElement);
      }
       
     }
     catch (Exception E)
     {
   System.out.println("Error in Highlight element");
  }
    }

Second Function


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public void mHighlightAndClick(WebDriver driver, WebElement vElement)
    {
     JavascriptExecutor js = (JavascriptExecutor)driver;
     try
     {
       js.executeScript("arguments[0].style.border='4px groove blue'", vElement);
          Thread.sleep(1000);
          
          vElement.click();                             
     }
     catch(Exception E)
     {
      System.out.println("Error in Highlight and click on element");
     }
    }


Please comment if you have any question.


Tuesday 27 February 2018

How to Do Database Connection in Selenium

Sometime in testing we need to validate data in database also or need to extract data from database. There are many type of database availabe now a days like MySQL, SQL, Oracle ect.

In this article we will see how to connect to database and execute query with selenium webdriver.

If we want execute query into database then we have to connect to that database first.

If you are using C# in Selenium then please go to below URL.
How to Do Database Connection in Selenium C#

How to connect to database?

Database would be local or on server also. So we need to first set class for database.

Syntax:

1
2
3
Class.forName("com.mysql.jdbc.Driver"); // For Local

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // For on server

Now we have to connect database.

Syntax:

1
sqlConnection = DriverManager.getConnection("ConnetionString", "Username", "Password"); 

We are done with database connection. Now, we have to execute query on database.

Syntax:


1
2
Statement st = sqlConnection.createStatement();
ResultSet rs = st.executeQuery(vQuery);

You get result of query in object of Resultset. you can use resultset values as per your requirement.Once you are done with your stuff then you have to close database connection.

Syntax:


1
sqlConnection.close();

Please go to below blog for database operation in selenium wrapper automation.

Database Operation with Selenium Wrapper Automation



Database Operations with Selenium Wrapper Automation

When you need to connect with database and execute query then you have to do first connect with your database then execute query.

Suppose you have scenario in that you need to execute lots of query and get result and verfy the result. So, for that every time you need to open connection, execute query and close connection. It is not good approach for any framework.

I have created one class 'DatabaseOperations' for different operation on database. you can use this class into your automation framework and use all methods of it with object of this class.


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import org.openqa.selenium.WebDriver;

public class DatabaseOperations 
{
 
 public Connection mConnectToServerDatabase(WebDriver driver, String vDatabaseName, String vUsername, String vPassword)
 {
  Connection sqlConnection = null;
  try
  {
   // Make database connection
   Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
  }
  catch (ClassNotFoundException E)
  {
   System.out.println("Error-SQL class not found.");
   E.printStackTrace();
  }
  
  try
  {
   // Get Database connection
   String vConnetionString = "jdbc:sqlserver://server ip\\QA:1444;databaseName";   
   sqlConnection = DriverManager.getConnection(vConnetionString, vUsername, vPassword);   
  }
  catch (Exception E)
  {
   System.out.println("Error in connection with database.");
   E.printStackTrace();
  }
  
  return sqlConnection;  
 }
 
 public Connection mConnectToLocalDatabase(WebDriver driver, String vDatabaseName, String vUsername, String vPassword)
 {
  Connection sqlConnection = null;
  try
  {
   // Make database connection
   Class.forName("com.mysql.jdbc.Driver");
  }
  catch (ClassNotFoundException E)
  {
   System.out.println("Error-SQL class not found.");
   E.printStackTrace();
  }
  
  try
  {
   // Get Database connection
   String vConnetionString = "jdbc:mysql://localhost:3306/user";   
   sqlConnection = DriverManager.getConnection(vConnetionString, vUsername, vPassword);   
  }
  catch (Exception E)
  {
   System.out.println("Error in connection with database.");
   E.printStackTrace();
  }
  
  return sqlConnection; 
 }
 
 public String[][] mExecuteQueryOnDatabase(WebDriver driver, Connection sqlConnection, String vQuery) throws SQLException
 {  
  int vRowCount, vColumnCount;  
 
  // Execute Query
  Statement st = sqlConnection.createStatement();
  ResultSet rs = st.executeQuery(vQuery);  
  ResultSetMetaData rsmd = rs.getMetaData();
     
  // Get row and column count
  vColumnCount = rsmd.getColumnCount();
  rs.last();
  vRowCount = rs.getRow();   
  rs.first();
        
  System.out.println("Number of Column in result : " + vColumnCount);
  System.out.println("Number of Row in result : " + vRowCount);      
  
  String[][] vResult = new String[vRowCount][vColumnCount];
  
  // Convert result set into String array
  int i=0;
  while(rs.next())
  {
   for(int j=0; j<vColumnCount; j++)
   {
    vResult[i][j] = rs.getString(j+1);
   }
   i++;
  }
   
  try
  {
   sqlConnection.close();
  }
  catch (SQLException E) 
  {   
   E.printStackTrace();
  }
  
  return vResult;
 }
 
 public String[][] mConnectDatabaseAndExecuteQuery(WebDriver driver, String vDatabaseType, String vDatabaseName, String vUsername, String vPassword, String vQuery) throws SQLException
 {
  Connection sqlConnection = null;
  
  if(vDatabaseType.equalsIgnoreCase("local"))
  {
   sqlConnection = mConnectToLocalDatabase(driver, vDatabaseName, vUsername, vPassword);
  }
  else if(vDatabaseType.equalsIgnoreCase("server"))
  {
   sqlConnection = mConnectToServerDatabase(driver, vDatabaseName, vUsername, vPassword);
  }
  
  String[][] vResult = mExecuteQueryOnDatabase(driver, sqlConnection, vQuery);
  
  return vResult;
 }
   
}


Please add comment if you have any question.

How to Handle Configuration File in Selenium

When we are working on automation framework then we have to follow such strategy so we can avoid hard code value as much as we can.

There are many parameters in every framework we can be changed frequently for running test case on different environemnt as well as with different configuration. So, we can not use hard code value for such parameters. We have to use configuration file for this scenario.

In that file, we can store all the parameters which are used in framework like browser name, browser type, application URL etc.

If you are using C# in selenium then go to below link for reading configuration file.
How to Read Configuration File in Selenium C#

We have to create one method to access value of those parameters from configuraiton file.

First of all we have to create one configuratioj file. Please follow below step.


  1. Create Configs folder under src folder
  2. Right click on Configs folder
  3. Go to New > File
  4. Give file name 'Configuration.properties'

Now add parameters which you are going to use in your framework.






Now, we have to create one method to access all these values of parameters. For that I have created one class 'ConfigFileReader'. I have created all methods for accessing values that class.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class ConfigFileReader 
{
 
 private Properties properties;
 private final String propertyFilePath= "Configs/Configuation.properties";
 
 
 public ConfigFileReader(){
  BufferedReader reader;
  try {
   reader = new BufferedReader(new FileReader(propertyFilePath));
   properties = new Properties();
   try {
    properties.load(reader);
    reader.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
   throw new RuntimeException("Configuration.properties not found at " + propertyFilePath);
  }  
 }
 
 public String getChromeDriverPath()
 {
  String driverPath = properties.getProperty("chromeDriverPath");
  if(driverPath!= null) return driverPath;
  else throw new RuntimeException("driverPath not specified in the Configuration.properties file.");  
 }
 
 public String getBrowserName()
 {
  String browserName = properties.getProperty("browserName");
  if(browserName!= null) return browserName;
  else throw new RuntimeException("Browser name not specified in the Configuration.properties file.");  
 }
 
 public String getBrowserType()
 {
  String browserType = properties.getProperty("browserType");
  if(browserType!= null) return browserType;
  else throw new RuntimeException("Browser Type not specified in the Configuration.properties file.");  
 }
 
 public long getImplicitlyWait()
 {  
  String implicitlyWait = properties.getProperty("ImplicitlyWait");
  if(implicitlyWait != null) return Long.parseLong(implicitlyWait);
  else throw new RuntimeException("implicitlyWait not specified in the Configuration.properties file.");  
 }
 
 public String getApplicationUrl()
 {
  String url = properties.getProperty("appURL");
  if(url != null) return url;
  else throw new RuntimeException("APP URL not specified in the Configuration.properties file.");
 }
 
 public String getTestDataSheetPath()
 {
  String path = properties.getProperty("testDataSheetPath");
  if(path != null) return path;
  else throw new RuntimeException("Test data sheet not specified in the Configuration.properties file.");
 }

}

You can see I have created separate function for access value of particular parameter. So you have to create separate function for all parameters. 

Please add comment if you have any question.

How to Compare Two Images in Selenium

Some time in testing we have to do image comparision as verification point. So, in this blog I expalin how to compare two images in selenium.

I have created one function for compare two images. you can use directly into your framework.

first of all you have to import below packages into your code.

import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

Now, you can use below function for comparison of two images.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public boolean mCompareImages(BufferedImage img1, BufferedImage img2)
 {
  boolean bCompareImage = true;
  try
  {
   if (img1.getWidth() == img2.getWidth() && img1.getHeight() == img2.getHeight())
   {
    for (int i = 0; i < img1.getWidth(); i++)
    {
     for (int j = 0; j < img1.getHeight(); j++)
     {
      if (img1.getRGB(i, j) != img2.getRGB(i, j))
      {
       bCompareImage = false;
      }
     }
    }
   }
   else
   {
    bCompareImage = false;
   }   
  }
  catch(Exception E)
  {
   bCompareImage = false;
  }
  
  return bCompareImage;
 }


Here, we are comparing tow images first in terms of heights and width. If Height and Width both are same then we are comparing RGB components of both images. If RGB components are same then images are same otherwise it is different.

Function is return Boolean value. If images are same then true and not same then false.

Please add comment if you have any question.

Monday 26 February 2018

Implicit Wait Vs. Explicit Wait Vs. Fluent Wait

When we do automation in selenium then waits for element is most important part in automation.

Why We Need Wait In Selenium?

When any page is load then different elements take different time to load or visible on page. So, if we do not handle wait in automation then "ElementNotVisibleException" exception will be thrown.

So, we have to handle waits in automation framework to overcome synchronization problem.

We can handle wait in three ways.
  1. Implicit Wait
  2. Explicit Wait
  3. Fluent Wait

Implicit Wait :

This wait will tell web driver to wait certain amoutn of time before thrown "ElementNotVisibleException" exception.

Syntax:

1
driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public class Test 
{
 
 public WebDriver driver;

 @Test
 public void TestWait() throws InterruptedException 
 {
 System.setProperty ("webdriver.chrome.driver",".\\chromedriver.exe" );
 driver = new ChromeDriver(); 
 driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;

 driver.findElement(By.id("txtUserId")).sendKeys(vUsername);   
 driver.findElement(By.id("txtPassword")).sendKeys(vPassword);
 driver.findElement(By.id("btnSignIn")).click();

 }

}

In above example, you can see timeout is for 10 seconds. So web driver will wait for 10 seconds if any element is not visible on page and after 10 seconds it will throw "ElementNotVisibleException" exception.


Explicit Wait :

This wait will tell web driver to wait till certain condition (Expected Condition) or maximum amount of time before throwing an "ElementNotVisibleException" exception.

Explicit wait is smart type of wait but it can only be applied specific elements. Once we declared explicit wait then we have to declare "Expected Condition" till which we want to wait.

Syntax:


1
WebDriverWait wait = new WebDriverWait(WebDriver,TimeOut);

Example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Test 
{
 
 public WebDriver driver;

 @Test
 public void TestExplicitWait() throws InterruptedException 
 {
 System.setProperty ("webdriver.chrome.driver",".\\chromedriver.exe" );
 driver = new ChromeDriver(); 
 
 WebDriverWait wait = new WebDriverWait(driver, 15);

 driver.findElement(By.id("txtUserId")).sendKeys(vUsername);   
 driver.findElement(By.id("txtPassword")).sendKeys(vPassword);

 WebElement SignIn = wait.until(ExpectedConditions.elementToBeClickable(By.id("btnSignIn")));

 SignIn.click(); 

 }
}

In above example, you can see first we set webdriverwait for 15 seconds. It means it will wait maximum 15 seconds then we set expected condition "elementToBeClickable" for SignIn element.

There are many expected conditions. We can use any of them as per our requirement.


Fluent Wait :

The fluent wait will tell the web driver to wait for a condition, as well as the frequency with which we want to check the condition before throwing an "ElementNotVisibleException" exception.

Frequency: it is repeat cycle with the time to verify the condition at the regular interval of time.

you can also specify Exception which you want to ignore to throw when webdriver is checking for particular element.

Syntax:


1
2
3
4
Wait wait = new FluentWait(WebDriver reference)
.withTimeout(timeout, SECONDS)
.pollingEvery(timeout, SECONDS)
.ignoring(Exception.class);

Example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Test 
{
 
 public WebDriver driver;

 @Test
 public void TestFluentWait() throws InterruptedException 
 {
 System.setProperty ("webdriver.chrome.driver",".\\chromedriver.exe" );
 driver = new ChromeDriver(); 
 
 Wait wait = new FluentWait(driver)
   .withTimeout(20, TimeUnit.SECONDS)    
   .pollingEvery(3, TimeUnit.SECONDS)    
   .ignoring(NoSuchElementException.class);

 driver.findElement(By.id("txtUserId")).sendKeys(vUsername);   
 driver.findElement(By.id("txtPassword")).sendKeys(vPassword);

 WebElement SignIn = wait.until(new Function() {
 
        public WebElement apply(WebDriver driver) {
 
        return driver.findElement(By.id("btnSignIn"));
 
        }
 
       });

 SignIn.click(); 

 }
}


In above example, you can see maximum timeout is set for 20 seconds.
Frequency is set for every 3 seconds by ignoring "NoSuchElementExecption".

Popular