Automation Using Selenium Webdriver

Sunday, 2 October 2016

POM Framework Using With Page Factory and With out Page Factory


Page Object Model using Selenium Webdriver and Implementation


1- It is design pattern in which will help you to maintain the codeand code duplication,
  which is a crucial thing in Test automation.

2- You can store all locators and respective methods inthe separateclass and Call them from the test in which you have to use.So the benefit from this will be if any changes in Page the you do not have to modify the test simply modify the respective page and that all.

3- You can create a layer between your test script and application page, which you have to automate.

4- In other words, it will behave as Object repository where all locators are saved.

“Please don’t get confused if you are using Object repository concept then do not use Page Object model because both will serve the same purpose.
Implementation of Page Object model using Selenium WebdriverIf you want to implement
 Page Object model then you have two choices and you can use any of it.

1 – Page Object model without PageFactory

2- Page Object Model with Pagefactory.

Personally, I am a big fan of Page Factory, which comes with Cache Lookup feature, which allows me to store frequently used locators in catch so that performance will be faster. We will discuss both you can implement based on your preferences.

Page Object Model With out page Factory


  Let’s take very basic scenario which you can relate to any application. Consider you have login page where username, password, and login button is present.

I will create a separate Login Page, will store three locators, and will create methods to access them. Kindly refer below screenshot for reference.
Now I want to design test case so I can use the Login class, which I created and can call the methods accordingly.
This Login class will be used by all the scripts, which you will create in future so if any changes happened then you have to update only Login Class not all the test cases. This sounds good right.
Program for Page Object Model using Selenium Webdriver without Page factory
package com.Facebook.Pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

/**
* @author jagan


* This class will store all the locator and methods of login page
*
*/
public class LoginPage 
{
WebDriver driver;
By username=By.id("user_login");
By password=By.xpath(".//*[@id='user_pass']");
By loginButton=By.name("wp-submit");
public LoginPage(WebDriver driver)
{
this.driver=driver;
}
public void loginToFacebook(String userid,String pass)
{

driver.findElement(username).sendKeys(userid);
driver.findElement(password).sendKeys(pass);
driver.findElement(loginButton).click();
}
public void typeUserName(String uid)
{
driver.findElement(username).sendKeys(uid);
}
public void typePassword(String pass)
{
driver.findElement(password).sendKeys(pass);
}
 public void clickOnLoginButton()
{
driver.findElement(loginButton).click();
}
}
TestCase using Page Object Model using Selenium Webdriver
package com.Facebook.Testcases;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

import com.Facebook.Pages.LoginPage;

/**
* @author Jagan
*
*/
public class VerifyFacebookLogin 
{
@Test
public void verifyFacebookLogin()
{
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.facebook.com");
LoginPage login=new LoginPage(driver):
login.clickOnLoginButton();
driver.quit();
}
}
Page Object Model using Selenium Webdriver with Page Factory
Selenium has built in class called PageFactory, which they mainly created for Page Object purpose, which allows you to store elements in cache lookup.

The only difference, which you will get without PageFactory and with PageFactory, is just initElement statement.Let us check the code and will see what changes required for with PageFactory Approach


Code for Page Object Model Using Selenium Webdriver using Page Factory

package com.Facebook.Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class LoginPageNew 
{
WebDriver driver;
public LoginPageNew(WebDriver ldriver)
{
this.driver=ldriver;
}
@FindBy(id="user_login") 
@CacheLookup
WebElement username; 
@FindBy(how=How.ID,using="user_pass")
@CacheLookup
WebElement password;
@FindBy(how=How.XPATH,using=".//*[@id='wp-submit']")
@CacheLookup
WebElement submit_button;
@FindBy(how=How.LINK_TEXT,using="Lost your password?")
@CacheLookup
WebElement forget_password_link;
public void login_Facebook(String uid,String pass)
{
username.sendKeys(uid);
password.sendKeys(pass);
submit_button.click();
} 
}
                Test Case using Page Factory

package com.facebook.Testcases;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;
import com.wordpress.Pages.LoginPage;
import com.wordpress.Pages.LoginPageNew;
import Helper.BrowserFactory;
public class VerifyValidLogin 
{
 @Test
public void checkValidUser()
{
// This will launch browser and specific url 
WebDriver driver=BrowserFactory.startBrowser("firefox", "http://www.facebook.com");
// Created Page Object using Page Factory
LoginPageNew login_page=PageFactory.initElements(driver, LoginPageNew.class);
// Call the method
login_page.login_wordpress("jagan", "jagan768");
}
}




Saturday, 1 October 2016

How to perform Advance activity in Selenium like- Mouse Hover, RightClick, DoubleClick, Keyboard Event

How to perform Advance activity in Selenium like- Mouse Hover, RightClick, DoubleClick, Keyboard Event



If you really want to automate critical applications, which include advance activity like Mouse Hover, Right click, Double click, Click and Hold, Keyboard activities and so on.

You cannot automate Ajax application, which contains advance activity so let us have a look.

you can also try Drag and Drop in Selenium using Action class

You do not have to worry about all this because all will come in single bundle i.e. you can perform all this using Actions class in Selenium.

Method name and Usage

moveToElement(WebElement)-- Mouse Hover

contextClick()-- Right click on page

contextClick(WebElement)-- Right click on specific Element

sendKeys(KEYS.TAB)--For keyboard events

clickAndHold(WebElement)--Click on element and hold until next operation

release() Release the current control
Usage of Mouse Hover- Handle Autosuggestion in SeleniumNow a days its default feature of almost
all the application take an example of Google itself when you type some words on search box, it gives some related suggestion.To achieve this we will use first mouse hover on element then click.

Scenario for Naukri.com autosuggestion-

First we will enter keywords using sendKeys() method then we have to wait for some time (2 or 3 seconds) to load suggestion and once it is loaded we will use mouse hover event using moveToElement() method of action class then we will click on that particular Item using click(Webelement) method of actions class.

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 AutoSuggestion {

public static void main(String[] args) throws InterruptedException {

WebDriver driver=new FirefoxDriver();

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

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

// Type something on Skill textbox
driver.findElement(By.id("qp")).sendKeys("test");

// Create object on Actions class
Actions builder=new Actions(driver);

// find the element which we want to Select from auto suggestion
WebElement ele=driver.findElement(By.xpath(".//*[@id='autosuggest']/ul/li[2]/a"));

// use Mouse hover action for that element
builder.moveToElement(ele).build().perform();

// Give wait for 2 seconds
Thread.sleep(2000);

// finally click on that element
builder.click(ele).build().perform();
}


}
Right Click in Selenium Webdriver

As we discussed earlier for right-click on a particular link or anyweb-element Selenium Webdriver has contextClick() methods available in Actions class.

There are two flavors of this

1-contextClick()- which will right Click on a page
2-contextClick(WebElement) – which will right click on a particular web-element.
Program 1-Below is the program to right click on a link in Google Home page

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;
public class TestRightClick {
@Test
public void TestClick() throws Exception
{
WebDriver driver=new FirefoxDriver();
driver.get(“http://www.google.com”);
driver.manage().window().maximize();
Actions act=new Actions(driver);
act.contextClick(driver.findElement(By.linkText(“andrapradesh”))).perform();
}
}
Keyboard events using Actions class.

For this we will use previous example after right click we will
select second option from list for this we will use ARROW_DOWN key
two times then we will hit ENTER Key.

Let’s implement the same

mport org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class GoogleTC {

public static void main(String[] args) {


WebDriver driver=new FirefoxDriver();

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

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

Actions act=new Actions(driver);

act.contextClick(driver.findElement(By.linkText("Andrapradesh"))).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();

}

}

Friday, 30 September 2016

Write Excel in Selenium Using Apache POI

Write Excel in Selenium Using Apache POI

In below example I am Writing .xlsx file

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.testng.annotations.Test;

public class ReadandWriteExcel {

 public static void main(String []args){

  try {

  // Specify the file path which you want to create or write

  File src=new File("./testdata/test.xlsx");

  // Load the file

  FileInputStream fis=new FileInputStream(src);

   // load the workbook

   XSSFWorkbook wb=new XSSFWorkbook(fis);

  // get the sheet which you want to modify or create

   XSSFSheet sh1= wb.getSheetAt(0);

 // getRow specify which row we want to read and getCell which column

 System.out.println(sh1.getRow(0).getCell(0).getStringCellValue());

 System.out.println(sh1.getRow(0).getCell(1).getStringCellValue());

 System.out.println(sh1.getRow(1).getCell(0).getStringCellValue());

 System.out.println(sh1.getRow(1).getCell(1).getStringCellValue());

 System.out.println(sh1.getRow(2).getCell(0).getStringCellValue());

 System.out.println(sh1.getRow(2).getCell(1).getStringCellValue());

// here createCell will create column

// and setCellvalue will set the value

 sh1.getRow(0).createCell(2).setCellValue("2.41.0");

 sh1.getRow(1).createCell(2).setCellValue("2.5");

 sh1.getRow(2).createCell(2).setCellValue("2.39");


// here we need to specify where you want to save file

 FileOutputStream fout=new FileOutputStream(new File("location of file/filename.xlsx"));


// finally write content

 wb.write(fout);

// close the file

 fout.close();

  } catch (Exception e) {

   System.out.println(e.getMessage());

  }

 }

}
Please comment in below section if you are facing any issue. Thanks For visiting my blog keep in touch

Thursday, 29 September 2016

Read data from Excel files in Selenium Using Apache POI

Read and Write Excel Programs


I am Reading simple .xlsx file

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.Test;


public class ReadandWriteExcel {

 public static void main(String []args){

  try {
  // Specify the path of file
  File src=new File("filepath/excelsheetname.xlsx");

   // load file
   FileInputStream fis=new FileInputStream(src);

   // Load workbook
   XSSFWorkbook wb=new XSSFWorkbook(fis);
 
   // Load sheet- Here we are loading first sheetonly
      XSSFSheet sh1= wb.getSheetAt(0);

  // getRow() specify which row we want to read.

  // and getCell() specify which column to read.
  // getStringCellValue() specify that we are reading String data.


 System.out.println(sh1.getRow(0).getCell(0).getStringCellValue());

 System.out.println(sh1.getRow(0).getCell(1).getStringCellValue());

 System.out.println(sh1.getRow(1).getCell(0).getStringCellValue());

 System.out.println(sh1.getRow(1).getCell(1).getStringCellValue());

 System.out.println(sh1.getRow(2).getCell(0).getStringCellValue());

 System.out.println(sh1.getRow(2).getCell(1).getStringCellValue());

  } catch (Exception e) {

   System.out.println(e.getMessage());

  }

 }

}

How to take screen shots of all page links in web site Automatically

How to take screen shots of all page links in web site Automatically


How to take screen shots of all page links in a web site automatically in Chrome driver using Selenium Web Driver.

Below Example Best Check it and Execute Programme   

package ScreenShot;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;


public class LinksScreenshot 
   {
//TestCase id:1 Step1:Decp
//TestCase id:1 Step2:Launch Chrome
//TestCase id:1 Step3:Navigate to newtours.demoaut
//TestCase id:1 Step4:Capture all links
//TestCase id:1 Step5:click on the all links and take screen shots
//Test Case id:1 Step6:close the browser

public static void main(String[] arg) throws IOException

{
 System.out.println("**********excution will stat wait**************");

 System.setProperty("webdriver.chrome.driver",  "C:\\chromedriver.exe");
 WebDriver driver=new ChromeDriver();
         driver.get("http://newtours.demoaut.com/");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
       List<WebElement> links=driver.findElements(By.tagName("a"));
        System.out.println("no of links:" +links.size());

      for(int i=0;i<links.size();i++)
      {
          if((links.get(i).isDisplayed()))
          {
          String linkname=links.get(i).getText();
                 links.get(i).click();
                
             File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(scrFile, new File("E:\\Jagan\\ScreenShot"+linkname+"png"));
   

          driver.navigate().back();
         

          links=driver.findElements(By.tagName("a"));
          
          }     
         
      }
      driver.close();
 }
        
          }       
      

      //OutPut:No of Links:16 We did get
 
 


  

Wednesday, 28 September 2016

Polymorphism in Java

Polymorphism in Java

The process of representing one form in multiple forms is known as Polymorphism.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.
Polymorphism is not a programming concept but it is one of the principal of OOPs. For many objects oriented programming language polymorphism principle is common but whose implementations are varying from one objects oriented programming language to another object oriented programming language.

Real life example of polymorphism

Suppose if you are in class room that time you behave like a student, when you are in market at that time you behave like a customer, when you at your home at that time you behave like a son or daughter, Here one person present in different-different behaviors.real life example of polymorphism

How to achieve Polymorphism in Java ?

In java programming the Polymorphism principal is implemented with method overriding concept of java.
Polymorphism principal is divided into two sub principal they are:
  • Static or Compile time polymorphism
  • Dynamic or Runtime polymorphism
Note: Java programming does not support static polymorphism because of its limitations and java always supports dynamic polymorphism.

Let us consider the following diagram

Here original form or original method always resides in base class and multiple forms represents overridden method which resides in derived classes.
polymorphism in java
In the above diagram the sum method which is present in BC class is called original form and the sum() method which are present in DC1 and DC2 are called overridden form hence Sum() method is originally available in only one form and it is further implemented in multiple forms. Hence Sum() method is one of the polymorphism method.

Example of runtime polymorphism.

In below example we create two class Person an Employee, Employee class extends Person class feature and override walk() method. We are calling the walk() method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, subclass method is invoked at runtime. Here method invocation is determined by the JVM not compiler, So it is known as runtime polymorphism.

Example of Polymorphism in Java

class Person
{
void walk()
{
System.out.println("Can Run....");
}
}
class Employee extends Person
{
void walk()
{
System.out.println("Running Fast...");
}
public static void main(String arg[])
{
Person p=new Employee(); //upcasting
p.walk();
}
}

Output

Running fast...

Dynamic Binding

Dynamic binding always says create an object of base class but do not create the object of derived classes. Dynamic binding principal is always used for executing polymorphic applications.
The process of binding appropriate versions (overridden method) of derived classes which are inherited from base class with base class object is known as dynamic binding.
Advantages of dynamic binding along with polymorphism with method overriding are.
  • Less memory space
  • Less execution time
  • More performance

Static polymorphism

The process of binding the overloaded method within object at compile time is known as Static polymorphism due to static polymorphism utilization of resources (main memory space) is poor because for each and every overloaded method a memory space is created at compile time when it binds with an object. In C++ environment the above problem can be solve by using dynamic polymorphism by implementing with virtual and pure virtual function so most of the C++ developer in real worlds follows only dynamic polymorphism.

Dynamic polymorphism

In dynamic polymorphism method of the program binds with an object at runtime the advantage of dynamic polymorphism is allocating the memory space for the method (either for overloaded method or for override method) at run time.

Conclusion

The advantage of dynamic polymorphism is effective utilization of the resources, so java always use dynamic polymorphism. Java does not support static polymorphism because of its limitation.

Encapsulation

Encapsulation in Java

Encapsulation is a process of wrapping of data and methods in a single unit is called encapsulation. Encapsulation is achieved in java language by class concept.
Combining of state and behavior in a single container is known as encapsulation. In java language encapsulation can be achieve using class keyword, state represents declaration of variables on attributes and behavior represents operations in terms of method.

Advantage of Encapsulation

The main advantage of using of encapsulation is to secure the data from other methods, when we make a data private then these data only use within the class, but these data not accessible outside the class.

Real life example of Encapsulation

The common example of encapsulation is capsule. In capsule all medicine are encapsulated in side capsule.
real life example of encapsulation

Benefits of encapsulation

  • Provides abstraction between an object and its clients.
  • Protects an object from unwanted access by clients.
  • Example: A bank application forbids (restrict) a client to change an Account's balance.

Let's see the Example of Encapsulation in java

Example

class Employee
{  
private String name;  
   
public String getName()
{  
return name;  
}  
public void setName(String name){  
this.name=name;
}  
}  

class Demo
{  
public static void main(String[] args)
{  
Employee e=new Employee();  
e.setName("Harry");  
System.out.println(e.getName());  
}  
}  

Output

Harry