Automation Using Selenium Webdriver

Tuesday, 8 November 2016

Test Case Grouping using TestNG ‘Groups’ Annotations

TestNG allows us to group several tests together. You can group certain tests based on what behavior/aspect they are actually testing. You may have a scenario where few tests belong to a certain group(say Regression) and other ones belong to other group(say Sanity) and yet another one belong to other group(say Login). With this approach you may decide to execute only certain group of test and skip other ones(let’s say there was a regression on related code, so we prefer to only execute Sanity related tests).The group test is a new innovative feature in TestNG, it doesn’t exist in Junit framework
Method annotated with @BeforeGroups gets executed only once for a group before any of the test of that group executes. Method annotated with @AfterGroups gets executed only once for a group only after all of the tests of that group finished execution.
Let’s see this with a simple example:
Review a test group example.
  1. checkMail(),deleteMail() and composeMail() are belong to group ‘Sanity’.
  2. checkDrafts(), checkAccountDetails() and checkPromotions() are belong to group ‘Regression’.
  3. If i chose to execute only ‘Sanity’ then Step1 should be  executed.
package samples;
import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
public class TestNG_Groups {
@BeforeGroups(“Login”)
public void login_Account() {
System.out.println(“Account Login”);
}
@Test(groups = “Sanity”)
public void checkMail() {
System.out.println(“Checking Mail in the Inbox”);
}
@Test(groups = “Regression”)
public void checkDrafts() {
System.out.println(“Checking Drafts”);
}
@Test(groups = “Regression”)
public void checkPromotions() {
System.out.println(“Checking Promotions”);
}
@Test(groups = “Regression”)
public void checkAccountDetails() {
System.out.println(“Checking Account Details”);
}
@Test(groups = “Sanity”)
public void composeMail() {
System.out.println(“Send a Mail “);
}
@Test(groups = “Sanity”)
public void deleteMail() {
System.out.println(“Delete a Mail”);
}
@AfterGroups(“Login”)
public void logout_Account() {
System.out.println(“Account Logout”);
}
}
Now create testng.xml file,
<suite name=”Build 2.0.1″>
<test name=”groups Test”>
<classes>
<class name=”samples.TestNG_Groups” />
</classes>
<groups>
<run>
<include name=”Sanity” />
</run>
</groups>
</test>
</suite>


When you run this xml only the Sanity testcases should be executed.We can also use ‘exclude’ to exclude desired testcases.

Monday, 7 November 2016

How To Set Proxy Settings In Selenium WebDriver Test

How To Set Proxy Settings In Selenium WebDriver Test
Sometimes, You need to set proxy settings of browser to run your selenium webdriver test.
 As you know, selenium launch fresh browser every time you run test so default proxy setting
will be No Proxy. You can set It In two ways.
1. Creating firefox profile and then use that profile In selenium test.
2. Using DesiredCapabilities. We will use DesiredCapabilities of selenium to set proxy.
What is DesiredCapabilities?
Using DesiredCapabilities, we can set and configure webdriver browser driver Instance
settings before launching It. Simplest example Is -> I wants to set proxy settings for
my webdriver browser Instance. I can do It using DesiredCapabilities.

How to set proxy settings of browser using DesiredCapabilities
I have created simple example to set proxy settings for firefox browser. It will set firefox driver
 browser Instance proxy settings as bellow.

HTTP Proxy = localhost, Port = 8080
SSL Proxy = localhost, Port = 8080
FTP Proxy = localhost, Port = 8080
SOCKS Host = localhost, Port = 8080

Example to set proxy for firefox driver Instance.
package Testing_Pack;

import java.io.IOException;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class ProxySettings {

 WebDriver driver;

 @BeforeTest
 public void setUpDriver() {
  //Set proxy IP and port. Here localhost Is proxy IP and 8080 Is Port number.
  //You can change both values as per your requirement.
  String PROXY = "localhost:8080";
  //Bellow given syntaxes will set browser proxy settings using DesiredCapabilities.
  Proxy proxy = new Proxy();
  proxy.setHttpProxy(PROXY).setFtpProxy(PROXY).setSslProxy(PROXY)
    .setSocksProxy(PROXY);
  DesiredCapabilities cap = new DesiredCapabilities();
  cap.setCapability(CapabilityType.PROXY, proxy);
  //Use Capabilities when launch browser driver Instance.
  driver = new FirefoxDriver(cap);
 }

 @Test
 public void start() throws IOException {
  System.out.println("Check your webdriver driver Instance's proxy setttings.");
 }
}

Run above example In your eclipse. It will open firefox browser driver Instance.
Check proxy settings for It from browser menu Tools -> Options -> Advanced tab -> Network tab -> Settings button. Click on Settings button. It will open connection settings popup as bellow.



You can see that proxy settings are set as given In test DesiredCapabilities configuration.
 You can change proxy IP and port number as per your requirement.


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"));
 
   }
  }