Automation Using Selenium Webdriver

Monday, 7 November 2016

Maximize browser window using webdriver

Maximize browser window using webdriver


There are times when we want to to maximize the browser window during the execution of our script .For this purpose webdriver providers a built-in method and here is the syntax :

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

Here is the sample code using TestNG framework. :
import java.awt.Toolkit;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Reporter;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class MaximizeWindow {

WebDriver driver;

@BeforeTest
public void setUpDriver() {
driver = new FirefoxDriver();
      }
  

@Test
public void maximize() {
 //declare varibales for windows
org.openqa.selenium.Dimension defaultDim;
org.openqa.selenium.Dimension maximizeDim;
//Load google website on browser
driver.get("http://google.com");
//Display the current screen dimensions
defaultDim=driver.manage().window().getSize();
System.out.println("screenHeight before maximizing"+defaultDim.getHeight());
System.out.println("screenWidth before maximizing"+defaultDim.getWidth());
//maximize the window using webdriver method
driver.manage().window().maximize();
//Display the maximized window dimensions
maximizeDim=driver.manage().window().getSize();
System.out.println("screenHeight after maximizing:"+maximizeDim.getHeight());
System.out.println("screenWidth after maximizing:"+maximizeDim.getWidth());

      }


  }

Sunday, 6 November 2016

Advanced Real time Grouping Test Methods | TestNG Process

Test Methods are annotated with @Test;  These methods can be grouped and executed separately using TestNG framework.
The methods can also be executed based on the priority.

Please find a Test Suite with real-time implementation as given below,

public class classname{
private WebDriver driver;
private String baseUrl;

  @BeforeTest(groups = { "Group1", "Group2" })
  public void setUp() throws Exception {
    driver = new FirefoxDriver();
    baseUrl = "http://www.justdial.com";
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  }

  @Test(groups = { "Group1" }, priority=3)
  public void test1() throws Exception {
    driver.get(baseUrl + "/");
    driver.findElement(By.id("what")).sendKeys("G1a");
    driver.findElement(By.id("where")).sendKeys("Chennai");
    System.out.println("I am G1a");
  }

  @Test(groups = { "Group1" }, priority=2)
  public void test2() throws Exception {
    driver.get(baseUrl + "/");
    driver.findElement(By.id("what")).sendKeys("G1b");
    driver.findElement(By.id("where")).sendKeys("Chennai");
    System.out.println("I am G1b");
  }

  @Test(groups = { "Group2" })
  public void test3() throws Exception {
    driver.get(baseUrl + "/");
    driver.findElement(By.id("what")).sendKeys("G2a");
    driver.findElement(By.id("where")).sendKeys("Chennai");
    System.out.println("I am G2a");
  }

  @Test(groups = { "Group1" }, priority=1)
  public void test4() throws Exception {
    driver.get(baseUrl + "/");
    driver.findElement(By.id("what")).sendKeys("G1c");
    driver.findElement(By.id("where")).sendKeys("Chennai");
    System.out.println("I am G1c");
  }

  @Test(groups = { "Group2" })
  public void test5() throws Exception {
    driver.get(baseUrl + "/");
    driver.findElement(By.id("what")).sendKeys("G2b");
    driver.findElement(By.id("where")).sendKeys("Chennai");
    System.out.println("I am G2b");
  }

  @AfterTest(groups = { "Group1", "Group2" })
  public void tearDown() throws Exception {
    driver.quit();  
  }

Create .xml file and replace the code

Right-click on your Project/Class file > TestNG > "Convert to TestNG" > Replace with the xml code given below > Finish

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="none">
<test name="Test1">
  <classes>
    <class name="package.classname"></class>
  </classes>
  <groups>
    <run>
      <include name="Group1"/>    
    </run>
  </groups>
</test>
</suite> <!-- Suite -->

Friday, 4 November 2016

Handling Drag & Drop for HTML5 | Robot [Webdriver]

Usual drag & drop doesn't work on pages built with HTML5. Here, I've used Robot for controlling the Mouse Actions to work with HTML5 websites.

Snippet

@Test
public void dragAndDrop() throws AWTException, InterruptedException {

driver.get("http://demo.kaazing.com/forex/");
Actions builder = new Actions(driver);
WebElement sourceElement = driver.findElement(By.xpath("(//li[@name='dragSource'])[13]"));
Action drag = builder.clickAndHold(sourceElement).build();
drag.perform();
 
WebElement targetElement = driver.findElement(By.xpath("//section[@id='section1']/div[2]"));
Point coordinates = targetElement.getLocation();
Robot robot = new Robot(); //Robot for controlling mouse actions
robot.mouseMove(coordinates.getX(),coordinates.getY()+120);
Thread.sleep(5000);
}

Note| Java Robot can also be used for various actions like locating tooltips, etc.,

Thursday, 3 November 2016

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&#8221;);
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();

}

}

How to get row count,column count in Excel useful for selenium

How to get row count,column count in Excel useful for selenium
In this post I am going to explain how can we get row count,column count in excel file with the help of Java using Apache POI jar libraries.
 Download Apache POI jar libraries in following link  and configure to your project.
 Download Apache POI jar

Sample code:
import org.apache.poi.xssf.usermodel.*;
import java.io.*;

public class Xls_Reader
{
 public  String path;
 public  FileInputStream fis = null;
 public  FileOutputStream fileOut =null;
 private XSSFWorkbook workbook = null;
 private XSSFSheet sheet = null;
 private XSSFRow row   =null;
 private XSSFCell cell = null;
 public static String sActionKeyword=null;


 //Constructor for path configuration
 public Xls_Reader(String path)
 {

  this.path=path;
  try
  {
   fis = new FileInputStream(path);
   workbook = new XSSFWorkbook(fis);
   sheet = workbook.getSheetAt(0);
   fis.close();
  }
  catch (Exception e)
  {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }
  // returns number of  rows in a sheet
  public int getRowCount(String sheetName)
  {
   int index = workbook.getSheetIndex(sheetName);
   if(index==-1)
    return 0;
   else
   {
   sheet = workbook.getSheetAt(index);
   int number=sheet.getLastRowNum()+1;
   return number;
   }
 
  }
        // returns number of columns in a sheet
  public int getColumnCount(String sheetName)
  {
   // check if sheet exists
   if(!isSheetExist(sheetName))
    return -1;
 
   sheet = workbook.getSheet(sheetName);
   row = sheet.getRow(0);
 
   if(row==null)
    return -1;
 
   return row.getLastCellNum();
  }
         // find whether sheets exists
  public boolean isSheetExist(String sheetName)
  {
   int index = workbook.getSheetIndex(sheetName);
   if(index==-1){
    index=workbook.getSheetIndex(sheetName.toUpperCase());
     if(index==-1)
      return false;
     else
      return true;
   }
   else
    return true;
  }
  //usage
  public static void main(String[] args){
 
   Xls_Reader xls = new Xls_Reader("C:/Users/Sudharsan/Desktop/TestData.xlsx");
   System.out.println(xls.isSheetExist("Login"));
   System.out.println(xls.getRowCount("Login"));
   System.out.println(xls.getColumnCount("Login"));
 
   }
  }

Java Difference Between

Difference Between

Difference between non-static and static variable ?

Non-Static methodStatic method
1These method never be preceded by static keyword
Example:
void fun1()
{
 ......
 ......
}
These method always preceded by static keyword
Example:
static void  fun2()
{
......
......
}
2Memory is allocated multiple time whenever method is calling.Memory is allocated only once at the time of loading.
3It is specific to an object so that these are also known as instance method.These are common to every object so that it is also known as member method or class method.
4These methods always access with object reference
Syntax:
Objref.methodname();
These property always access with class reference
Syntax:
className.methodname();
5If any method wants to be execute multiple time that can be declare as non static.If any method wants to be execute only once in the program that can be declare as static .

Difference between Method and Constructor

MethodConstructor
1Method can be any user defined nameConstructor must be class name
2Method should have return typeIt should not have any return type (even void)
3Method should be called explicitly either with object reference or class referenceIt will be called automatically whenever object is created
1Method is not provided by compiler in any case.The java compiler provides a default constructor if we do not have any constructor.

Difference between package keyword and import keyword

  • Package keyword is always used for creating the undefined package and placing common classes and interfaces.
  • import is a keyword which is used for referring or using the classes and interfaces of a specific package.

Difference between Class and Object

ClassObject
1Class is a container which collection of variables and methods.object is a instance of class
2No memory is allocated at the time of declarationSufficient memory space will be allocated for all the variables of class at the time of declaration.
3One class definition should exist only once in the program.For one class multiple objects can be created.

Difference between Statement and PreparedStatement ?

StatementPreparedStatement
1Statement interface is slow because it compile the program for each executionPreparedStatement interface is faster, because its compile the command for once.
2We can not use ? symbol in sql command so setting dynamic value into the command is complexWe can use ? symbol in sql command, so setting dynamic value is simple.
3We can not use statement for writing or reading binary data (picture)We can use PreparedStatement for reading or writing binary data.

Difference between throw and throws ?

throwthrows
1throw is a keyword used for hitting and generating the exception which are occurring as a part of method bodythrows is a keyword which gives an indication to the specific method to place the common exception methods as a part of try and catch block for generating user friendly error messages
2The place of using throw keyword is always as a part of method body.The place of using throws is a keyword is always as a part of method heading
3When we use throw keyword as a part of method body, it is mandatory to the java programmer to write throws keyword as a part of method headingWhen we write throws keyword as a part of method heading, it is optional to the java programmer to write throw keyword as a part of method body.

Difference between checked Exception and un-checked Exception ?

Checked ExceptionUn-Checked Exception
1checked Exception are checked at compile timeun-checked Exception are checked at run time
2e.g.
IOException, SQLException, FileNotFoundException etc.
e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberNotFoundException etc.

Difference between Abstraction and Encapsulation ?

Encapsulation is not provides fully security because we can access private member of the class using reflation API, but in case of Abstraction we can't access static, abstract data member of class.

Difference between Abstract and Interface ?

AbstractInterface
1It is collection of abstract method and concrete methods.It is collection of abstract method.
2There properties can be reused commonly in a specific application.There properties commonly usable in any application of java environment.
3It does not support multiple inheritance.It support multiple inheritance.
4Abstract class is preceded by abstract keyword.It is preceded by Interface keyword.
5Which may contain either variable or constants.Which should contains only constants.
6The default access specifier of abstract class methods are default.There default access specifier of interface method are public.
7These class properties can be reused in other class using extend keyword.These properties can be reused in any other class using implements keyword.
8Inside abstract class we can take constructor.Inside interface we can not take any constructor.
9For the abstract class there is no restriction like initialization of variable at the time of variable declaration.For the interface it should be compulsory to initialization of variable at the time of variable declaration.
10There are no any restriction for abstract class variable.For the interface variable can not declare variable as private, protected, transient, volatile.
11There are no any restriction for abstract class method modifier that means we can use any modifiers.For the interface method can not declare method as strictfp, protected, static, native, private, final, synchronized.

Difference between Overloading and Overriding ?

OverloadingOverriding
1Whenever same method or Constructor is existing multiple times within a class either with different number of parameter or with different type of parameter or with different order of parameter is known as Overloading.Whenever same method name is existing multiple time in both base and derived class with same number of parameter or same type of parameter or same order of parameters is known as Overriding.
2Arguments of method must be different at least arguments.Argument of method must be same including order.
3Method signature must be different.Method signature must be same.
4Private, static and final methods can be overloaded.Private, static and final methods can not be overrided.
5Access modifiers point of view no restriction.Access modifiers point of view not reduced scope of Access modifiers but increased.
6Also known as compile time polymorphism or static polymorphism or early binding.Also known as run time polymorphism or dynamic polymorphism or late binding.
7Overloading can be exhibited both are method and constructor level.Overriding can be exhibited only at method leve.
8The scope of overloading is within the class.The scope of Overriding is base class and derived class.
9Overloading can be done at both static and non-static methods.Overriding can be done only at non-static method.
10For overloading methods return type may or may not be same.For overriding method return type should be same.

Difference between sleep() and suspend() ?

Sleep() can be used to convert running state to waiting state and automatically thread convert from waiting state to running state once the given time period is completed. Where as suspend() can be used to convert running state thread to waiting state but it will never return back to running state automatically.

Difference between String and StringBuffer ?

StringStringBuffer
1The data which enclosed within double quote (" ") is by default treated as String class.The data which enclosed within double quote (" ") is not by default treated as StringBuffer class
2String class object is immutableStringBuffer class object is mutable
3When we create an object of String class by default no additional character memory space is created.When we create an object of StringBuffer class by default we get 16 additional character memory space.

Difference between StringBuffer and StringBuilder ?

All the things between StringBuffer and StringBuilder are same only difference is StringBuffer is synchronized and StringBuilder is not synchronized. synchronized means one thread is allow at a time so it thread safe. Not synchronized means multiple threads are allow at a time so it not thread safe.
StringBufferStringBuilder
1It is thread safe.It is not thread safe.
2Its methods are synchronized and provide thread safety.Its methods are not synchronized and unable to provide thread safety.
3Relatively performance is low because thread need to wait until previous process is complete.Relatively performance is high because no need to wait any thread it allows multiple thread at a time.
1Introduced in 1.0 version.Introduced in 1.5 version.

Difference between Method and Constructor ?

MethodConstructor
1Method can be any user defined nameConstructor must be class name
2Method should have return typeIt should not have any return type (even void)
3Method should be called explicitly either with object reference or class referenceIt will be called automatically whenever object is created
1Method is not provided by compiler in any case.The java compiler provides a default constructor if we do not have any constructor.

Difference between non-static and static Method

Non-Static methodStatic method
1These method never be preceded by static keyword
Example:
void fun1()
{
 ......
 ......
}
These method always preceded by static keyword
Example:
static void  fun2()
{
......
......
}
2Memory is allocated multiple time whenever method is calling.Memory is allocated only once at the time of class loading.
3It is specific to an object so that these are also known as instance method.These are common to every object so that it is also known as member method or class method.
4These methods always access with object reference
Syntax:
Objref.methodname();
These property always access with class reference
Syntax:
className.methodname();
5If any method wants to be execute multiple time that can be declare as non static.If any method wants to be execute only once in the program that can be declare as static .

Difference between non-static and static variable

Non-static variableStatic variable
1These variable should not be preceded by any static keyword Example:
class  A
{
int a;
}
These variables are preceded by static keyword.

Example

class  A
{
static int b;
}
2Memory is allocated for these variable whenever an object is createdMemory is allocated for these variable at the time of loading of the class.
3Memory is allocated multiple time whenever a new object is created.Memory is allocated for these variable only once in the program.
4Non-static variable also known as instance variable while because memory is allocated whenever instance is created.Memory is allocated at the time of loading of class so that these are also known as class variable.
5Non-static variable are specific to an objectStatic variable are common for every object that means there memory location can be sharable by every object reference or same class.
6Non-static variable can access with object reference.

Syntax

obj_ref.variable_name
Static variable can access with class reference.

Syntax

class_name.variable_name

Wednesday, 2 November 2016

Checking text on web page using WebDriver

While testing any web application, we need to make sure that it is displaying correct text under given elements. Selenium WebDriver provides a method to achieve this. We can retrieve the text from any WebElement using getText() method.

Example
Lets create a test that check for the proper text in flipkart menu tab.

Code:
@Test
public void testFlipkartMenuText() {
    //Get Text from first item and store it in String variable
    String electronics = driver.findElement(By.cssSelector("li[data-key='electronics']>a>span")).getText();
 
    //Compare actual & required texts
    assertEquals("Electronics",electronics); 
}
The WebElement class' getText() method returns value of the innerText attribute
of the element.

P.S : Given script may not work on flipkart site. I've written this code just to give some basic idea of using getText() method