Tuesday, July 30, 2019

Example of POM in selenium WebDriver | What is Page Object model in selenium ?

What Page object mode?

-Page object model in simple term is an design pattern you create in your Test Framework which helps you to manage your code.

lets look at the example below,

Image result for page object model

POM is design patter we will create to manage our code easily.
in which we will create a Two classes.
One class is for defining all the locators and actions of a page.
Second class is for using that locators and actions and perform operation on it.


Why We should choose POM?

Non POM layout:-
In Non POM layout means without any design pattern suppose we are writing a Login test than what we do in it is

Step 1 :-
Create a java class than we define WebDriver and than Define WebElement and using that WebElement we perform action on it in that class.

like,

package facebook;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class facebook2 {

 public static void main(String[] args) {
  System.setProperty("webdriver.chrome.driver","C:\\Users\\5558\\eclipse-workspace\\chromedriver.exe");
  System.out.println("hello");
  WebDriver driver = new ChromeDriver();
  System.out.println("hello");
  driver.get("https://www.facebook.com");
  System.out.println("hello");
  driver.manage().window().maximize();
  driver.findElement(By.xpath(".//*[@id='email']")).sendKeys("divyangjani@gmail.com");
  driver.findElement(By.xpath(".//*[@id='pass']")).sendKeys("dixit1234");
  driver.findElement(By.xpath(".//*[@id='u_0_2']")).click();
  driver.quit();
  

 }

}


Suppose , after creating this because of some reason Locator of any button is changed. so in this case we have to go to the every place in our code and change that element's locator manually.

and this action will be very time consuming and annoying.


But,

If we Use design pattern of POM than our code will be :-

This is the First class in which we are defining all the locators of a page.


package facebook;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class webelement {
 
 static WebDriver driver;
 static WebElement element;
 
 public webelement(WebDriver driver) {
        //super();
        this.driver = driver;
    }

 
 public static WebElement firstname() {
  
  element=driver.findElement(By.xpath("//input[@name='firstname']"));
  return element; 
 }
 public static WebElement lastname()
 {
  element=driver.findElement(By.xpath("//input[@name='lastname']"));
  return element;
 }
 public static WebElement email()
 {
  element=driver.findElement(By.xpath("//input[@name='reg_email__']"));
  return element;
 }
 public static WebElement newpassword()
 {
  element=driver.findElement(By.xpath("//input[@name='reg_passwd__']"));
  return element;
 }
 public static WebElement day()
 {
  element=driver.findElement(By.xpath("//select[@name='birthday_day']"));
  return element;
 }
 
 public static WebElement month()
 {
  element=driver.findElement(By.xpath("//select[@name='birthday_month']"));
  return element;
  
 }
 public static WebElement year()
 {
  element=driver.findElement(By.xpath("//select[@name='birthday_year']"));
  return element;

 }
 public static WebElement sex()
 {
 element=driver.findElement(By.xpath("(//input[@name='sex'])[2]"));
 return element;
 
 }
 
 public static WebElement signup() {
  element=driver.findElement(By.xpath("//button[@name='websubmit']"));
  return element;
 }
 
 
 public void set_firstname(String fname)
 
 {
       firstname().sendKeys(fname); 
 }
 }


And this is the class where we will use this locators and actions to perform operation.

package facebook;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.io.FileHandler;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;

import facebook.facebook;
import wixlogin.TakeScreenshot;
public class signup {
 static WebDriver driver;
 @Test
 public void login()

 {
 
  System.setProperty("webdriver.chrome.driver","C:\\Users\\5558\\eclipse-workspace\\chromedriver.exe");
  driver=new ChromeDriver();
  driver.get("https://www.facebook.com");
  driver.manage().timeouts().implicitlyWait(2000, TimeUnit.MILLISECONDS);
  driver.manage().window().maximize();
  webelement ele = new webelement(driver);
  
  //ele.firstname().sendKeys("dixit");
  ele.set_firstname("test");
  
  ele.lastname().sendKeys("jani");
  ele.email().sendKeys("test@gmail.com");
  
  ele.newpassword().sendKeys("dixit1234");

  Select day = new Select(ele.day());

  day.selectByIndex(24);
  
  Select month = new Select(ele.month());
  
  month.selectByVisibleText("Jul");
  
  Select year = new Select(webelement.year());
  year.selectByVisibleText("1997");
  ele.sex().click();

  ele.signup().click();
    
  }

 @AfterTest
 public void close_browser()
 {
  driver.close();
  
 }
 }



Now if you look at this code and Non POM class code , you will notice that it is very eye catching to easy and easy to handle. while Non POM code looks complex to understand what is going on?


I hope this article helps you :)
if you like this article than please do share it with your freinds/colleagues.

Monday, July 29, 2019

How to take screenshot in selenium? | TakesScreenShot interface in selenium | How to take screenshot of a fail test in Selenium WebDriver ?

Sometimes you may have feel uncertainty when you are running you test and test goes fail than you need to capture a screenshot of your failed Test case.

Capturing screenshot in selenium is very easy. it can be done by TakesScreenshot interface.

Copy this below code and paste it in your class at the step where your test is failing.


TakesScreenshot ts=(TakeScreenshot)driver;
  File file=ts.getScreenshotAs(OutputType.FILE);
  try {
   FileHandler.copy((File) ts,new File("./screenshot/login.png"));
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

Step 1:- Create a class and write the test code.

Step 2:- Paste this code where you test is failing.

Here in code, i am storing this screenshot as "login.png" but for your use you can give it other name too. i would suggest to use timestemp_filename to save the screenshot.

lets look at the code now,




package wixlogin;

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

import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.io.FileHandler;

public class Login {

 public static void main(String[] args) {
  System.setProperty("webdriver.chrome.driver","C:\\Users\\5558\\eclipse-workspace\\chromedriver.exe");
  WebDriver driver=new ChromeDriver();
  driver.get("http://dixitjani666.wixsite.com/mysite");
  driver.manage().window().maximize();
  driver.findElement(By.id("ggl-login-text")).click();
  driver.findElement(By.xpath(".//*[@id='view_container']/form/div[2]/div/div/div[1]/ul/li[2]/div")).click();
 
  TakesScreenshot ts=(TakeScreenshot)driver;
  File file=ts.getScreenshotAs(OutputType.FILE);
  try {
   FileHandler.copy((File) ts,new File("./screenshot/login.png"));
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  driver.close();
  
 }

}


Step 3:- Run this class file. when your test is get executed you will see a screenshot folder in your project folder. in that you will get the PNG file of your test.


I hope this will helpful to you :) if you guys find it helpful than please share it with others :)

Happy learning!

Sunday, July 28, 2019

How to Test a Selenium Script Parallel in Multiple Browser ?| TestNG parameters tag |How to create a TestNG.xml file ?? | Cross Browser Testing |

Suppose , if we have a single script and that we need to run on multiple browsers at a same time than rather than creating two separate class for each browser we can do it with the TestNG's parameter tag.

How?

let me show it

Step 1:-
- Create a new java class. and create a method with @BeforeTest annotation of TestNG. and take the parameter's name ( Browser's name ) on which test is going to run inside that method.


@Parameters("Browsername")
 
 @BeforeTest
 public void setup(String Browsername)

Step 2:-

Write a code for setting up a Web Driver based on the based on the Browser's name.

@BeforeTest
 public void setup(String Browsername)
 {
  if(Browsername.equalsIgnoreCase("chrome"))
  {
         System.setProperty("webdriver.chrome.driver","C:\\Users\\5558\\eclipse-workspace\\chromedriver.exe");
    
        driver = new ChromeDriver();
  }
  
  if(Browsername.equalsIgnoreCase("firefox"))
  {
   System.setProperty("webdriver.gecko.driver","C:\\Users\\5558\\eclipse-workspace\\geckodriver.exe");
   driver = new FirefoxDriver();
  }
  
  
 }

Step 3:- Create a @Test method and write your test code in that method.

Step 4:- Create @AfterTestMethod and write a code to close the browser.


Step 6:-

Right click on that class file and go to Testng >> Convert To TestNG class





and Create a testng.xml file of a class.

this file will be show in TestNG folder of your project.


Step 7:-  configure testng.xml file like this image below.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite thread-count="2" name="Suite" parallel="tests">
  <test name="TestChrome">
  <parameter name="Browsername" value="chrome"> </parameter>
    <classes>
      <class name="mmt.crossbrowsers"/>
    </classes>
  </test>
   
   <test name="Testff">
  <parameter name="Browsername" value="firefox"> </parameter>
    <classes>
      <class name="mmt.crossbrowsers"/>
    </classes>
  </test> 
  
  
  </suite> 


here, Parameter name is should be same as we have declared in class and its value refers to the browser on which test is going to run.

in Suits tag Thread-counts will refer to the number of browsers in which our test will run.


Now ,
Right click on this testng.xml file and run it with the testng

it will open a chrome browser and firefox browser parallely , than opens a url specified , it will print a title of a page.

you can Add IE browser in this suit and method too. but remember one thing , we need to run testng.xml file and not a class file otherwise it will give an error.



i hope this article helps you guys :) if you like it useful and please share it with others too.
also if you have any query than comment down below i will try my level best to answer it to you :)


Thanks! 

Sunday, July 21, 2019

X-Path extensions in chrome browser | How to find X-path | X-path Tricks | Ruto extensios

If you are beginner in automation field and writing basic test script, first common issue you would feel is to finding X-path.

We know we have Firebug and Firepath plugin for finding x-path but it has limitation

- It works only in Firefox
-Also, it is available for older version of the firefox


I have found one of the Extension for finding X-path which will work in Chrome browser. also it is  very easy to use.

Step 1:-
Go to Chrome Web store.

Step 2:-

Search for Ruto , you will get this extension




Install it from here.it will be added into you extension list in chrome.


How to use Ruto?


Step 1 :-

 Go to any site ( i.e google.com )

Step 2:-

Right Click on any WebElement on page.

it will show Ruto in options.




Step 3:-

Click on "Add to ruto" , it will show notification on the Ruto icon' s like this



like this you will get x-path of any WebElement using different selectors.


i found it very useful. i hope you guys also like it.

How to record a script using selenium webdriver?

While doing automation we come across the scenario where our script dont run as expected and we need to show someone what is happening , so that time we need to record our script.

So, that thing we can easily do with the ATUTestRecorder library.

Step 1:-

Download ATUTestRecorder library from here

Step 2:-


Right click on project> Go to build path > Configure build path


Step 3:-



Go to Add External jars and select the downloaded jar file


Step 4:-


Click on Apply and close

this will add that Jar file into your project path.

By refreshing on Refrence libraries you can see this jar file.




Step 5:-

write a code to record and stop the script.


ATUTestRecorder record = new ATUTestRecorder("E://Recording", "fb", false);
  record.start();



here you can use Date and time name to save this file, i have used simple name "fb" for easy understanding


This class will take 3 parameters ( 1 file location to save this file , 2nd name of the file , 3 rd is to save background audio)


to Stop recording,

record.stop();


Here i have sample class i have created one script which will record signup script of the facebook.



package facebook;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

import atu.testrecorder.ATUTestRecorder;
import atu.testrecorder.exceptions.ATUTestRecorderException;


public class facebook {

 public static void main(String[] args) throws ATUTestRecorderException {
  System.setProperty("webdriver.chrome.driver","C:\\Users\\5558\\eclipse-workspace\\chromedriver.exe");
  
  WebDriver driver = new ChromeDriver();
  ATUTestRecorder record = new ATUTestRecorder("E://Recording", "fb", false);
  record.start();
    

  driver.navigate().to("https://www.facebook.com");
  
  driver.findElement(By.xpath(".//*[@id='u_0_j']")).sendKeys("sam");
  driver.findElement(By.name("lastname")).sendKeys("jani");
  driver.findElement(By.id("u_0_o")).sendKeys("sam123@yahoo.com");
  driver.findElement(By.name("reg_passwd__")).sendKeys("dixit1234");
  
  Select sel = new Select(driver.findElement(By.name("birthday_day")));
     sel.selectByValue("24");
     Select month= new Select(driver.findElement(By.name("birthday_month")));
     month.selectByIndex(8);
     Select year = new Select(driver.findElement(By.name("birthday_year")));
     year.selectByVisibleText("1997");
     driver.findElement(By.xpath(".//*[@id='u_0_a']")).click();
     driver.findElement(By.xpath(".//*[@id='u_0_11']")).click();
    driver.findElement(By.xpath(".//*[@id='u_0_r']")).sendKeys("sam123@yahoo.com");
     driver.findElement(By.xpath(".//*[@id='u_0_11']")).click();
     record.stop();
     driver.close();
     
  
 }

}

Saturday, July 20, 2019

Data driven framework example in selenium

What is Data driven framework in selenium?

-in simple terms as per as name "Data driven" framework means a framework which is run by data.

Suppose if we are testing login feature of any site, that time we are dealing with multiple data combination i.e ( valid data , invalid data ). so that time dealing with those data become complex.

so if we make a framework which is data driven it will save a lot of time in testing, also it will reduce the complexity

so let me show you what i mean actually...



this is dummy file which have fake login credential.
if you dont have time to create dummy data than you can use this site

here the sheet name is "Sheet1"
now, i will write one Excel uttils class which will handle all the Excel related operations.

package utills;

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

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Excelutills {
 static XSSFWorkbook workbook;
 static XSSFSheet sheet;
 
 static String path=System.getProperty("user.dir");
public Excelutills(String wbook, String sheetname) throws IOException
{
 workbook=new XSSFWorkbook(wbook);
 sheet=workbook.getSheet(sheetname);
}
 

 public static String getdata(int row, int cell) throws IOException{
  
   String cellvalue = sheet.getRow(row).getCell(cell).getStringCellValue();
     // System.out.println("cell value is:"+cellvalue);
  return cellvalue;
  
 }
 public int rows_count() {
  int rows = sheet.getPhysicalNumberOfRows();
 
  return rows;
 }
 
 public int col_count(){
  
  int cellnum =sheet.getRow(0).getPhysicalNumberOfCells();
  //System.out.println("total number of cells are:"+cellnum);
  return cellnum;
  
 }

}



now, i will use this class's constructor so that i can use all the functions of this class into any another class.

You can also copy this code and use it in your use.


now i have created another class in which i will use this Excellutill class's method to create a data driven framework.



package utills;

import java.io.IOException;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class Data2 {
 WebDriver driver = null;
 
 public Object[][] testdata() throws IOException {
  
  String path=System.getProperty("user.dir");
  Excelutills data = new Excelutills(path+"/Excel/login.xlsx", "Sheet1");
  int row=data.rows_count();
  int col=data.col_count();
   
  
  Object[][] data2 = new Object[row-1][col];

  for(int i=1;i<row;i++)
   
  {
   for(int j=0;j<col;j++)
    
   {
    String values = Excelutills.getdata(i, j);
    
    data2[i-1][j]=values;
   }
   
   
  }
  
  return data2;
  
  
 }
 @DataProvider(name="logindata")
 public Object[][] test() throws IOException
 
 {
 
    Object[][] testdata= testdata();
 return testdata;       
 }
 
 @Test(dataProvider="logindata")
 public void logindata(String username, String password)
 {
   System.setProperty("webdriver.chrome.driver","C:\\Users\\5558\\eclipse-workspace\\chromedriver.exe");
  driver =  new ChromeDriver();
  driver.get("https://www.makemytrip.com");
  
  driver.manage().window().maximize();
  WebElement login = driver.findElement(By.xpath("(//li[contains(@class,'makeFlex hrtlCenter')])[5]"));
  login.click();
  WebElement username1 = driver.findElement(By.id("username"));
  WebElement password1 = driver.findElement(By.id("password"));
  username1.sendKeys(username);
  password1.sendKeys(password);
  
 }

 
}


Guys i hope i helped you to explain this data driven framework 😄
this is my first ever post on bloggers so you might not like the presentation but i will keep posting new blogs about selenium webdriver,  as i am also learner like you :)


thank you for read this blog and if you like this blog please share it
-Thanks