Automation Using Selenium Webdriver

Thursday 6 October 2016

How to Create Object Repository in Selenium Webdriver- Selenium

Whenever you talk about repository by the name itself you can think thatit is kind of storage. Object repository is the collection of object and object here is locator.Object Repository in Selenium Webdriver is quite easy todesign so let’s get started.

Here locator means web element id, name, CSS, XPath, class name etc.

Object Repository in Selenium Webdriver

To understand an importance of Object repository, we will take real time scenario.

The scenario is you have 100 test cases and in all test cases, you have login scenario. If your application changes now and some locator changes like id changes from email to login email then you have to modify all the test cases and you have to change the id.

This process does not make any sense so to overcome with this we will move all locator in a separate file and we will link all test cases to this file.
In case any changes happen in our locator we will simply change in that file, not our test cases.

This will increase the modularity of test cases and I will strongly suggest thatyou should use Object Repository in Automation.

Object Repository in Selenium Webdriver- Selenium Tutorial Precondition

1- Project should be created and Selenium jars should be added- Click here to configure .

2- Now create a new file and give file name as Object_Repo (depends on you)with extension .
properties

For this right click on project > create a new file > Specify name




Select folder and specify name & extension


3- Now file is created > Double click on file > File will open in Edit mode
Object repository works on KEY and Value pair so we will specify Keys based on our project and in values we will give locator value.
In below example, I have taken xpath for username,password and loginbutton for facebook loginpage.
Key you can write based on your project standard, but value should be correct which is coming from application
<span style="font-size: 14pt; font-family: arial, helvetica, sans-serif;">
facebook.login.username.xpath=.//*[@id='email']
facebook.login.password.xpath=.//*[@id='pass']
facebook.login.Signup.xpath=.//*[@id='loginbutton']</span>



4- Write Selenium script and use the same in script

Object Repository in Selenium Webdriver- Selenium Tutorial

package ObjectRepoExample;
<span style="font-size: 14pt; font-family: arial, helvetica, sans-serif;">import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class TestFacebook {
@Test
public void TestOR() throws IOException{
// Specify the file location I used . operation here because
//we have object repository inside project directory only
File src=new File(".Object_Repo.properties");
// Create  FileInputStream object
FileInputStream fis=new FileInputStream(src);
// Create Properties class object to read properties file
Properties pro=new Properties();
// Load file so we can use into our script
pro.load(fis);
System.out.println("Property class loaded");
// Open FirefoxBrowser
WebDriver driver=new FirefoxDriver();
// Maximize window
driver.manage().window().maximize();
// Pass application
driver.get("http://www.facebook.com");
// Enter username here I used keys which is specified in Object repository.
// Here getProperty is method which
// will accept key and will return value for the same
driver.findElement(By.xpath(pro.getProperty("facebook.login.username.xpath"))).
sendKeys("Selenium@gmail.com");
// Enter password here I used keys which is specified in Object repository.
// Here getProperty is method which
// will accept key and will return value for the same
driver.findElement(By.xpath(pro.getProperty("facebook.login.password.xpath"))).
sendKeys("adsadasdas");
 / Click on login button here I used keys which is specified in Object repository.
// Here getProperty is method which
// will accept key and will return value for the same
driver.findElement(By.xpath(pro.getProperty("facebook.login.Signup.xpath"))).click(); 
}}
</span>

How to disable Selenium Testcases using TestNG Feature

How to disable Selenium Testcases using TestNG Feature




Welcome to Selenium Tutorial, Today we are going to discuss very silent feature of TestNG which allow us to enable or disable our test case based on our requirement.

Why to Disable Selenium Test cases?

Before moving forward you should have Eclipse TestNG setup ready if still not configured then please doSelenium Eclipse setup now.
Once our test suite size will increase day by day then chances are high that you don’t want to execute some test cases.
Ok so let’s consider a scenario that you have written 10 testcases but now you want to execute only 5 testcase because other 5 are working correctly

How to Disable Selenium Test cases?

In TestNG we can achieve this by simply adding enable attribute and can set value to true/false.
If test case enable as false them while running test cases TestRunner simply will ignore this testcase and will only run testcase whose enable is set to true.
Note- By default @Test is set to enable
Scenario – I have 3 test case but I want to execute only 2 test case.
Precondition- TestNG should be installed

Program for – Disable Selenium Test cases

import org.testng.annotations.Test;
public class TestEnableTC {
@Test
public void testLoginApp(){
System.out.println("User is able to login successfully");
}
@Test(enabled=false)
public void testRegisteruser(){
System.out.println("User is able to register successfully");
}
@Test
public void testLogoutApp(){
System.out.println("User is able to logout successfully");
}
}






Wednesday 5 October 2016

What is Cross Browser Testing in TestNG

                               What is Cross browser testing            
Cross browser, testing refers to testing the application in multiple browsers like IE, Chrome, Firefox so that we can test our application effectively.IE, Chrome, Firefox so that we can test our application effectively.

Cross browser, testing is very important concept in Automation because here the actual automation comes into the picture.

Example- Suppose if you have 20 test cases that you have to execute manually, so it is not a big deal right we can execute in 1 day or 2 days. However, if the same test cases you have to execute in five browsers it means 100 test cases then probably you will take one week or more than one week to do the same and it will be quite boring as well.

If you automate these 20 test cases and run them then it will not take more than one or two hour depends on your test case complexity.

Cross Browser Testing using Selenium Webdriver

To achieve this we will use TestNG parameter feature, we will pass parameter from TestNG.xml file, and based on our parameter Selenium will initiate our browsers.

In this scenario, we will run the same testcase with two different browser parallel.

Step 1- Write testcase
---------------------------------

package SampleTestcases;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class TestCase1 {

@Test

// Here this parameters we will take from testng.xml
@Parameters("Browser")
public  void test1(String browser) {

if(browser.equalsIgnoreCase("FF")){

WebDriver driver=new FirefoxDriver();

driver.manage().window().maximize();

driver.get("http://www.facebook.com");

driver.quit();

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

System.setProperty("webdriver.ie.driver", "./server/IEDriverServer.exe");

WebDriver driver=new InternetExplorerDriver();

driver.manage().window().maximize();

driver.get("http://www.facebook.com");

driver.quit();
}
}

}
 Step 2- Create testng.xml and specify
------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
Here parallel is an attribute which specify the mode of execution and thread-count specify how many browser should open
<suite name="Suite" parallel="tests" thread-count="2">

<test name="Test">

<parameter name="Browser" value="FF" />

<classes>

<class name="SampleTestcases.TestCase1"/>

</classes>

</test>

<test name="Test1">

<parameter name="Browser" value="IE" />

<classes>

<class name="SampleTestcases.TestCase1"/>

</classes>

</test>

</suite>
Step 3- Run this xml file refer the below screenshot
------------------------------------------------------

Note- To create testng.xml- Right, click on your testcase then go to TestNG then convert to TestNG> It will generate testng.xml then make changes as per above xml file and finish. You will get testng.xml file inside the project


























Tuesday 4 October 2016

Different ways to get all "404 page not found" links using Selenium WebDriver

In this post, I will explain the most convenient way using Selenium WebDriver to get all the links from web page and verifying each page contains specific like 404 or Page not found in different ways.

//Following ways to identify 404 links
By using page title
By using page source
By using response code of page URL     
  
Please find the below code for the same.
Sample Code:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class GetAllLinks {
 public WebDriver driver;
 ArrayList<String> al ;
 @BeforeClass
 public void setup(){
  driver = new FirefoxDriver();
  driver.get("http://www.facebook.com/");
  driver.manage().window().maximize();
  
 }
 @Test
 public void identifyBrokenAnd404Links() throws MalformedURLException, IOException{
  
      al = new ArrayList<String>();
  
    //identifying total number of URls in a page
    List<WebElement> links = driver.findElements(By.tagName("a")); 
    System.out.println(links.size());
   
           //for Getting all links from page
          for (int i = 0;i<links.size(); i++) {
      
        //get one by one URL href value
        String URL=links.get(i).getAttribute("href"); 
       
        //Removing unwanted URLS based on http or https
        if(links.get(i).getAttribute("href").contains("https")||links.get(i).getAttribute("href").contains("http"))
        {
        System.out.println(URL);
       
         //storing all in URL's in array list
         al.add(URL);
       
        }
          }
     
          //Identifying  broken and 404 links
         
          for(int i=0;i<al.size();i++){
           
           //Navigating each URL
           driver.get(al.get(i));
           
           //getting response Code for the link
           int statusCode= ResponseCode(al.get(i));

           //verifying 404 links using page title
           
           if(driver.getTitle().contains("404")){
            
            System.out.println("404 link is  "+al.get(i));
            
           }
           
           //verifying 404 links using page source
           else if(driver.getPageSource().contains("404 page not found")){
            
            System.out.println("404 link is  "+al.get(i));
            
           }
           //verifying 404 links using status code
           else if(statusCode==404){
            
            System.out.println("404 link is  "+al.get(i));
           } 
           
           
          } 
  }
    //method for generating response code for URL
     public static int ResponseCode(String URL) throws MalformedURLException, IOException {     
        URL url = new URL(URL); 
        HttpURLConnection huc = (HttpURLConnection) url.openConnection(); 
        huc.setRequestMethod("GET"); 
        huc.connect(); 
        return huc.getResponseCode(); 
     } 

}
              

Monday 3 October 2016

Data Driven Framework in Selenium Webdriver


             Data driven framework in selenium web driver 

this framework purely depends on data and data source can be anything like Excel file, CSV File, database.

In data driven framework script will be separated from Data part, it means so if any changes happen we do not have to modify all the test cases.

Example-
I have to create 50 Gmail accounts so I have two approaches to do this

First- I can create 50 scripts and run them.

Second- I can keep all data separate in the file and changes the data only that is required for script and script will be only one. In future, any changes in my application then I have to modify my one script only not fifty.

In simple words when we have to execute same script, multiple sets of data we will adopt data driven framework

In this post, we are taking data from 2D Array and feeding data into script

Scenario 1- Open Facebook and type username and password and login
this test case should run 2 times with different set of data(data we have provided in the 2D array)

Lest Implement the same

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class TestDDT {

// this will take data from dataprovider which we created
@Test(dataProvider="testdata")
public void TestFireFox(String uname,String password){

// Open browsre
WebDriver driver=new FirefoxDriver();


// Maximize browser
driver.manage().window().maximize();


// Load application
driver.get("http://www.facebook.com");


// clear email field

driver.findElement(By.id("email")).clear();


// Enter usename
driver.findElement(By.id("email")).sendKeys(uname);

// Clear password field
driver.findElement(By.id("pass")).clear();


// Enter password
driver.findElement(By.id("pass")).sendKeys(password);
}
// this is DataProvider which actually feed data to our test cases here I have taken 2 D //array with 2 rows and 2 column it means. It will run our test case two times because we //have taken 2 rows. While first iteration this will pass username and password to test //case and in second iteration perform the same for second rows

@DataProvider(name="testdata")
public Object[][] TestDataFeed(){

// Create object array with 2 rows and 2 column- first parameter is row and second is //column
Object [][] facebookdata=new Object[2][2];

// Enter data to row 0 column 0
facebookdata[0][0]="Selenium1@gmail.com";


// Enter data to row 0 column 1
facebookdata[0][1]="Password1";


// Enter data to row 1 column 0
facebookdata[1][0]="Selenium2@gmail.com";

// Enter data to row 1 column 0
facebookdata[1][1]="Password2";

// return arrayobject to testscript
return facebookdata;
}

}</span>

Data driven framework in selenium webdriver using Excel files
In above post, we have seen data driven using 2D array but once your test data will increase then you have to switch to Excel or CSV or Database.

Create some test data in Excel that we will pass to the script. For demo purpose, I have to take username and password in Excel.
Before implement the program please make sure you are familiar with Reading Data from Excel.
Copy below program and before executing make sure following Thing configured correctly.

Eclipse, TestNG, JExcel jar
Scenario -Open Facebook and login with different username and password
username and password will be coming from excel sheet

Note- in below program we have 2 rows only so test case will execute 2 times with different data
package DataDrivenTesting;

import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class TestDDT1 {

WebDriver driver;
Workbook wb;
Sheet sh1;
int numrow;
String username;
String password;

@BeforeTest
public void Setup()

{
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.facebook.com");
}

@Test(dataProvider="testdata")
public void TestFireFox(String uname,String password1)

{

driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys(uname);
driver.findElement(By.id("pass")).clear();
driver.findElement(By.id("pass")).sendKeys(password1);
}

@DataProvider(name="testdata")
public Object[][] TestDataFeed(){

try {

// load workbook
wb=Workbook.getWorkbook(new File("location of excel sheet/fbdata.xls"));

// load sheet in my case I am referring to first sheet only
sh1= wb.getSheet(0);

// get number of rows so that we can run loop based on this
numrow=  sh1.getRows();
}
catch (Exception e)

{
e.printStackTrace();
}

// Create 2 D array and pass row and columns
Object [][] facebookdata=new Object[numrow][sh1.getColumns()];

// This will run a loop and each iteration  it will fetch new row
for(int i=0;i<numrow;i++){

// Fetch first row username
facebookdata[i][0]=sh1.getCell(0,i).getContents();
// Fetch first row password
facebookdata[i][1]=sh1.getCell(1,i).getContents();

}

// Return 2d array object so that test script can use the same
return facebookdata;
}

@AfterTest
public void QuitTC(){

// close browser after execution
driver.quit();
}

}</span>

I hope you have enjoyed the data driven framework in selenium webdriver and Hope you will implement the same. If you still have any doubt then let me know in the comment section. You can implement the same data driven framework using POM (Page Object model ) which will be the advanced version of data driven framework in selenium webdriver.



Kindly share this with your friends as well