Monday 2 December 2013

Classpath Setup for Java - Windows

Purpose: Classpath Setup for Java - Windows 7

We all know the importance of CLASSPATH for Java. Setting PATH/CLASSPATH is very easy but some of us facing difficulties. For them I want to contribute from my blog. Following steps will provide how easy we can set CLASSPATH/PATH for Java.


Step 1: Download and install Java if not available on your box. You can download from the following URL:
http://www.oracle.com/technetwork/java/javase/downloads/index.html

Step 2: By default JDK will be install at "C:\Program Files\Java\jdkxxx.xx" location only. Unless we change the location at the time of installation this is the default location.

Step 3: Go to JDK installed location and you will find bin folder and open that one. copy the bin folder path.




Step 4: Right Click on My Computer and Select "Properties". Once the Properties window is opened click on Advanced System Settings.

Step 5: Once Advance System Settings window is opened click on Environment Variables option



Step 6: Once Environment Variables window is opened click on New under System Variables and enter Variable Name as PATH and Variable Values  as Path of Java Bin Folder(previously copied path) and click OK




Step 7: Go to JDK folder -> open lib folder and copy the path

 


Step 8: Repeat the steps 4 and 5. Now click on New under User Variables and enter User Variable as CLASS and Variable Values as Path of the lib folder and click on OK




Step 9:  Click on OK of Environment Variables window and System Properties window

Step 10: Open Command Prompt and run any java program and you are able to successfully complete.








 

Wednesday 27 November 2013

Executing same selenium script with multiple browsers only or cross browser testing - Opening Browsers Parallel

Purpose: Executing same selenium script with multiple browsers only or cross browser testing - Opening Browsers Parallel

In my previous post I provided one way of executing same script with different browsers. Now I am going to show how to run the same script parallel(opening all the browsers at time)

Only the change is very small but I wontedly keeping the post separately to avoid the confusion.

The parallel attribute on the <suite> tag can take one of following values:

<suite name="My suite" parallel="methods">

parallel="methods": TestNG will run all your test methods in separate threads. Dependent methods will also run in separate threads but they will respect the order that you specified.

<suite name="My suite" parallel="tests">

parallel="tests": TestNG will run all the methods in the same <test> tag in the same thread, but each <test> tag will be in a separate thread. This allows you to group all your classes that are not thread safe in the same <test> and guarantee they will all run in the same thread while taking advantage of TestNG using as many threads as possible to run your tests.

<suite name="My suite" parallel="classes">

parallel="classes": TestNG will run all the methods in the same class in the same thread, but each class will be run in a separate thread.

<suite name="My suite" parallel="instances">

parallel="instances": TestNG will run all the methods in the same instance in the same thread, but two methods on two different instances will be running in different threads.


From the above parameters: we will use parallel="tests" to achieve our goal.

Step 1: We need to write our case with small change by passing a parameter.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class MultiBrowser {
 private WebDriver driver;

 @Parameters("browser")
 @BeforeMethod
 public void setup(String browser)
 {
  if(browser.equalsIgnoreCase("firefox"))
  {
   driver = new FirefoxDriver();
  }
  else if(browser.equalsIgnoreCase("iexplorer"))
  {
// Update the driver path with your location
   System.setProperty("webdriver.ie.driver", "Drivers\\IEDriverServer.exe");
   driver = new InternetExplorerDriver();
  }
  else if(browser.equalsIgnoreCase("chrome"))
  {
// Update the driver path with your location
   System.setProperty("webdriver.chrome.driver", "Drivers\\chromedriver.exe");
   driver = new ChromeDriver();
  }
  driver.manage().window().maximize();
 }

 @AfterMethod
 public void tearDown()
 {
 driver.quit();
 }

 @Test
 public void testMultiBrowser() throws InterruptedException
 {
  driver.get("http://www.google.com");
  Thread.sleep(3000);
 }
}

2. Now we need to create TestNG.xml and write the following code:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="MultiBrowser">
       <test name="TestFirefox" verbose="10">
              <parameter name="browser" value="firefox" />
              <classes>
                     <class name="MultiBrowser" />
              </classes>
       </test>
       <test name="ChromeTest">
              <parameter name="browser" value="chrome" />
              <classes>
                     <class name="MultiBrowser" />
              </classes>
       </test>
       <test name="IETest">
              <parameter name="browser" value="iexplorer" />
              <classes>
                     <class name="MultiBrowser" />
              </classes>
       </test>
</suite>

3. Now run the code from TestNG.xml

You can observer all the three browsers will open and perform the task at a time.






 

Friday 22 November 2013

Executing same selenium script with multiple browsers onfly or cross browser testing

Purpose: Executing same selenium script with multiple browsers

Testing in multiple browsers or Browser compatibility Testing: these are the word we always bother while automating our Test Cases. Following code will help how to execute the same script with multiple browsers.

Step 1: We need to write our case with small change by passing a parameter.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class MultiBrowser {
 private WebDriver driver;

 @Parameters("browser")
 @BeforeMethod
 public void setup(String browser)
 {
  if(browser.equalsIgnoreCase("firefox"))
  {
   driver = new FirefoxDriver();
  }
  else if(browser.equalsIgnoreCase("iexplorer"))
  {
// Update the driver path with your location
   System.setProperty("webdriver.ie.driver", "Drivers\\IEDriverServer.exe");
   driver = new InternetExplorerDriver();
  }
  else if(browser.equalsIgnoreCase("chrome"))
  {
// Update the driver path with your location
   System.setProperty("webdriver.chrome.driver", "Drivers\\chromedriver.exe");
   driver = new ChromeDriver();
  }
  driver.manage().window().maximize();
 }

 @AfterMethod
 public void tearDown()
 {
 driver.quit();
 }

 @Test
 public void testMultiBrowser() throws InterruptedException
 {
  driver.get("http://www.google.com");
  Thread.sleep(3000);
 }
}

2. Now we need to create TestNG.xml and write the following code:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="MultiBrowser">
       <test name="TestFirefox" verbose="10">
              <parameter name="browser" value="firefox" />
              <classes>
                     <class name="MultiBrowser" />
              </classes>
       </test>
       <test name="ChromeTest">
              <parameter name="browser" value="chrome" />
              <classes>
                     <class name="MultiBrowser" />
              </classes>
       </test>
       <test name="IETest">
              <parameter name="browser" value="iexplorer" />
              <classes>
                     <class name="MultiBrowser" />
              </classes>
       </test>
</suite>

3. Now run the code from TestNG.xml

You can observer all the three browsers will open and perform the task one another.

Sunday 17 November 2013

Prioritizing Selenium Test cases using TestNG annotations

Purpose: Prioritizing Selenium Test cases using TestNG annotations

Some times we may need to priorities our test cases based on some requirements. Following code will help you all.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class PriorityParam {
 public WebDriver driver;
 public String baseURL;

 @BeforeMethod
 public void setup()
 {
  driver = new FirefoxDriver();
  driver.manage().window().maximize();
  baseURL = "http://mail.google.com";
 }

 @AfterMethod
 public void tearDown()
 {
  driver.quit();
 }

 @Test(priority=3)
 public void testPriorityParam() throws InterruptedException
 {
  driver.get(baseURL);
  Thread.sleep(3000);
  System.out.println("Priority 3");
 }

 @Test(priority=2)
 public void testPriorityParam1() throws InterruptedException
 {
  driver.get(baseURL);
  Thread.sleep(3000);
  System.out.println("Priority 2");
 }

 @Test(priority=4)
 public void testPriorityParam2() throws InterruptedException
 {
  driver.get(baseURL);
  Thread.sleep(3000);
  System.out.println("Priority 4");
 }

Thursday 14 November 2013

Different Operations on Combo Box / Dropdown / Select Option using Selenium Web Driver

Purpose: Different Operations on Combo Box / Dropdown using Selenium Web Driver

We always encounter Combo Box / Dropdown / Select options and following example will help you how to perform different operations.

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.openqa.selenium.support.ui.Select;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class SelectOption {
 public WebDriver driver;
 public String baseURL;

 @BeforeTest
 public void setup()
 {
  driver = new FirefoxDriver();
  driver.manage().window().maximize();
  baseURL = "http://hscripts.com/tutorials/html/form-combobox.php";
 }

 @AfterTest
 public void tearDown()
 {
  driver.quit();
 }

 @Test
 public void testSelectOption() throws InterruptedException
 {
  driver.get(baseURL);
 
  WebElement select = driver.findElement(By.xpath(".//form[1]/select"));
  WebElement multiSelect = driver.findElement(By.xpath(".//form[3]/select"));
  List<WebElement> selectedValues = new ArrayList<>();
 
  Select dropdown = new Select(select);
  dropdown.deselectAll();
  dropdown.selectByValue("two");
  selectedValues = dropdown.getAllSelectedOptions();
  for(WebElement value: selectedValues)
  {
   System.out.println("Selected Value: "+value.getText());
  }
  Thread.sleep(3000);
 
  dropdown = new Select(multiSelect);
  dropdown.deselectAll();
  dropdown.selectByValue("three");
  dropdown.selectByValue("four");
  selectedValues = dropdown.getAllSelectedOptions();
  for(WebElement value: selectedValues)
  {
   System.out.println("Selected Value: "+value.getText());
  }
  Thread.sleep(3000);
  dropdown.deselectAll();
  Thread.sleep(3000);
 }
}

Wednesday 16 October 2013

Reading Test Data from Text File and Writing in to Text File

Purpose: Reading Test Data from Text File and Writing in to Text File

Some times we may need to read test data from text file. We can achieve this using simple Java snippet. following code will help you to address this

import java.io.*;
public class ReadTextFile {
    public static void main(String[] args){
        String readFile ="D://test.txt";
        String writeFile ="D://test1.txt";
       
        //reading contents from a text file  
        try{
            InputStream ips=new FileInputStream(readFile);
            InputStreamReader ipsr=new InputStreamReader(ips);
            BufferedReader br=new BufferedReader(ipsr);
            String line;
            br.readLine();
           
            String[] n = null;
            while ((line =br.readLine())!=null){
             n = line.split(",");
             for(int i = 0; i < n.length; i++)
             {
              System.out.print(n[i]);
             }
             System.out.println("\n");
            }
            br.close();
        }      
        catch (Exception e){
            System.out.println(e.toString());
        }
        //writing to a text file
        try {
            FileWriter fw = new FileWriter (writeFile);
            BufferedWriter bw = new BufferedWriter (fw);
            PrintWriter fileOut = new PrintWriter (bw);
           
                fileOut.println ("\n1. Writing Content to text file");
                fileOut.println ("\n2. Writing content to text file");
               
            fileOut.close();
        }
        catch (Exception e){
            System.out.println(e.toString());
        }      
    }
}

Inupt file contents(test.txt):


First Name:, User First Name
Last Name:, User Last Name
User Name:, User Name
Password:, Password
Email:, email
First Name:, User First Name
Last Name:, User Last Name
User Name:, User Name1
Password:, Password1
Email:, email1
 

Sunday 29 September 2013

Reading an element contnet without using XPath by WebDriver

Purpose: Reading an element contnet without using XPath by WebDriver

Some times we can access an element with class only but the class contans compound values but className will not accept compound values.

In order to handle these situatuions we need to write differently. Following code will help you to handle it.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class Webelements {
 static WebDriver driver;
 // Browser startup
 @BeforeClass
 public void setup() {
 
  driver = new FirefoxDriver();
 }
 // Functionality of Test Case
 @Test
 public void testGoogle() throws InterruptedException, IOException {
 
  driver.get("http://quirksmode.org/css/selectors/multipleclasses.html");
//  System.out.println(driver.findElement(By.className("underline small")).getText());
  System.out.println(driver.findElement(By.cssSelector("p[class='underline small']")).getText());
 
  Thread.sleep(3000);
 }
 @AfterClass
 public void tear() {
  driver.close();
 }

Wednesday 25 September 2013

Expanding Tree Structure using Selenium Web Driver

Purpose: Expanding Tree Structure using Selenium Web Driver

Following code will help how to expand tree structure with the help of Selenium WebDriver. Every Tree Structure have its own levels. Following code will help to go 2 level expansion.

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.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TreeStructure {
 public String baseURL = "http://www.javascripttoolbox.com/lib/mktree/";

 public WebDriver driver = new FirefoxDriver();
 @BeforeMethod
 public void setup()
 {
  driver.get(baseURL);
 }

 @AfterMethod
 public void tear()
 {
  driver.quit();
 }

 @Test
 public void testTreeStructure() throws InterruptedException
 {
  driver.findElement(By.xpath("html/body/table/tbody/tr[2]/td[1]/div[2]/div[2]/p[6]/a[2]")).click();
  Thread.sleep(3000);
  List<WebElement> roots = driver.findElements(By.xpath(".//*[@id='tree1']/li"));
  int rootSize = 1;
  for(WebElement root: roots)
  {
   String openRoot = root.getAttribute("class");
   if(openRoot.equalsIgnoreCase("liClosed"))
   {
    String xpath = ".//*[@id='tree1']/li["+rootSize+"]/span";
    openTree(xpath);
    List<WebElement> childRoots = driver.findElements(By.xpath(".//*[@id='tree1']/li["+rootSize+"]/ul/li"));
    int subRootSize = 1;
    for(WebElement childRoot: childRoots)
    {
     String openSubRoot = childRoot.getAttribute("class");
     if(openSubRoot.equalsIgnoreCase("liClosed"))
     {
      String path = ".//*[@id='tree1']/li["+rootSize+"]/ul/li["+subRootSize+"]/span";
      openTree(path);
     }
     subRootSize = subRootSize+1;
    }
   }
   rootSize = rootSize+1;
  }
 }

 public void openTree(String xpath) throws InterruptedException
 {
  driver.findElement(By.xpath(xpath)).click();
  Thread.sleep(3000);
 }
}

Tuesday 24 September 2013

Handling different Javascript prompts using Selenium WebDriver

Purpose: Handling different Javascript prompts using Selenium WebDriver

We always come across different javascript prompts while accessing different websites. Follwoing code will help to handle while automating those functionalities.

This requires one web page which contains different ways to generate Javascript prompts. Following code for Web page

jscriptpopup.html

<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("This is a JavaScript Alert Box!")
document.getElementById("result").innerHTML="Alert Prompted";
}
function show_confirm()
{
 var r=confirm("Press a button");
 if (r==true)
   {
   x="Pressed OK Button!";
   document.getElementById("result").innerHTML=x;
   }
 else
   {
   x="Pressed Cancel Button!";
   document.getElementById("result").innerHTML=x;
   }
}
function show_prompt()
{
 var v = prompt("Enter Value");
 if(v!=null)
  document.getElementById("result").innerHTML="Entered Value is "+v;
  else
 document.getElementById("result").innerHTML="Pressed Cancel button";
}
</script>
</head>
<body>
<input type="button" onclick="show_alert()" value="Show Alert Box" />
<input type="button" onclick="show_confirm()" value="Show Confrim Box" />
<input type="button" onclick="show_prompt()" value="Show Prompt Box" />
<div id="result"></div>
</body>
</html>

Please save the above code and provide the location of the file in WebDriver code

Webdriver Code:

 import org.openqa.selenium.By;
import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class JscriptPop {

 public String baseURL = "file:///D:/Raju/Projects/Automation/Sample/jscriptpopup.html"; // Location of the source file
 public Alert alert;
 public static WebDriver driver=new FirefoxDriver();

 @BeforeMethod
 public void setup()
 {
  driver.get(baseURL);
 }

 @AfterMethod
 public void tear()
 {
  driver.quit();
 }

 @Test
 public void testJscriptPop() throws InterruptedException
 {
  // Clicking Alert Box
  driver.findElement(By.xpath("//input[@value='Show Alert Box']")).click();
  Thread.sleep(3000);
  alert = driver.switchTo().alert();
  Thread.sleep(3000);
  // To click ok
  alert.accept();
  Thread.sleep(3000);

  // Clicking Confirm Box
  driver.findElement(By.xpath("//input[@value='Show Confrim Box']")).click();
  Thread.sleep(3000);
  alert = driver.switchTo().alert();
  Thread.sleep(3000);
  // To click OK
  alert.accept();
  Thread.sleep(3000);

  // Clicking Confirm Box
  driver.findElement(By.xpath("//input[@value='Show Confrim Box']")).click();
  Thread.sleep(3000);
  alert = driver.switchTo().alert();
  Thread.sleep(3000);
  // To click Cancel
  alert.dismiss();
  Thread.sleep(3000);

  // Clicking Confirm Box Prompt Button
  driver.findElement(By.xpath("//input[@value='Show Prompt Box']")).click();
  Thread.sleep(3000);
  alert = driver.switchTo().alert();
  alert.sendKeys("Test value");
  Thread.sleep(3000);
  // To click OK
  alert.accept();
  Thread.sleep(3000);

  // Clicking Confirm Box Prompt Button
  driver.findElement(By.xpath("//input[@value='Show Prompt Box']")).click();
  Thread.sleep(3000);
  alert = driver.switchTo().alert();
  Thread.sleep(3000);
  // To click Cancel
  alert.dismiss();
  Thread.sleep(3000);
 }
}

Sunday 22 September 2013

Capturing contents of a Table using Selenium Web Driver

Purpose: Capturing contents of a Table using Selenium Web Driver

Some times we may need to capture each and every value from a table while automating. Following example will help to implement the requirement.

This example also will help us to capture nth Row & Column value.

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.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TableExample {
  public String baseURL = "http://accessibility.psu.edu/tablecomplexhtml";
  public WebDriver driver = new FirefoxDriver();
 
  @BeforeMethod
  public void setup()
  {
   driver.get(baseURL);
  }
 
  @AfterMethod
  public void tear()
  {
   driver.quit();
  }
 
  @Test
  public void testTableExample()
  {
   List<WebElement> rows = driver.findElements(By.xpath(".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr")); // Returns the number of Rows
   List<WebElement> cols = driver.findElements(By.xpath(".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr[1]/td")); // Returns the number of Columns
  
   // Static XPath of a single TR and TD is ".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr[1]/td[1]"
  
   // code to fetch each and every value of a Table
  
   for(int rowNumber = 1; rowNumber <= rows.size(); rowNumber++)
   {
    for(int colNumber = 1; colNumber <= cols.size(); colNumber++)
    {
     System.out.print(driver.findElement(By.xpath(".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr["+rowNumber+"]/td["+colNumber+"]")).getText()+"  ");
    }
    System.out.println("\n");
   }
  
   System.out.println("###############################################################################\n");

  // nth element value of a table
  
   System.out.println(driver.findElement(By.xpath(".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr["+rows.size()+"]/td["+cols.size()+"]")).getText());
  
  }
}

Wednesday 18 September 2013

Performing Mouse Double Click using Selenium Web Driver

Perpose: Performing Mouse Double Click using Selenium Web Driver

Some web applications may need to perform double click to fire the action. Following code will help how to implement Mouse Double Click using Selenium.

In the following example, page contans a div and if we perform single click noting is going to happen but when we perform double click Map will be zoomed.


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.Action;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class DoubleClick {
 public String baseURL = "http://openlayers.org/dev/examples/click.html";
 public WebDriver driver = new FirefoxDriver();
 public WebElement element;
 public String title;
 public Actions action = new Actions(driver);
 @BeforeTest
 public void launchBrowser()
 {
  driver.get(baseURL);
 }

 @AfterTest
 public void closeBrowser()
 {
  driver.quit();
 }

 @Test
 public void doubleClick() throws InterruptedException
 {
  element = driver.findElement(By.xpath(".//*[@id='OpenLayers_Map_2_OpenLayers_ViewPort']"));
  element.click();// For single click Map will not load
  System.out.println("Single Click performed");
  Thread.sleep(3000);
  Action doubleClick = action.doubleClick(element).build();
  doubleClick.perform();// After performing double click Map will load
  System.out.println("Double Click performed");
  Thread.sleep(10000);
  doubleClick.perform();// After performing double click Map will load
  System.out.println("Double Click performed");
  Thread.sleep(10000);
 }
}

Capturing the Sub Menu values using Selenium Web Driver

Purpose: Capturing the Sub Menu values using Selenium Web Driver

Some times we may need to validate the valus of Sub-menus. If static it is easy to implement but some times we may need to validate the dynamic data.

Following code will help to accomplish this:

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.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class DropDownCSSMenu {
 public String baseURL = "http://demo.lateralcode.com/css-drop-down-menus/";
 public WebDriver driver = new FirefoxDriver();
 public Actions action = new Actions(driver);
 public List<WebElement> elements;
 public int size;

 @BeforeTest
 public void launchBrowser()
 {
  driver.get(baseURL);
 }

 @AfterTest
 public void closeBrowser()
 {
  driver.quit();
 }

 @Test
 public void test() throws InterruptedException
 {
  WebElement home = driver.findElement(By.linkText("Home"));
  WebElement about = driver.findElement(By.linkText("About"));
  WebElement contact = driver.findElement(By.linkText("Contact"));
 
  action.moveToElement(home).build().perform();//MouseOver of Menu
  driver.findElement(By.xpath("//*[@id='menu']/ul/li[1]/ul/li[1]/a")).click(); //Clicking Sub Menu
  Thread.sleep(3000);
  elements = driver.findElements(By.xpath(".//*[@id='menu']/ul/li[1]/ul/li/a"));
  for (WebElement element : elements) {
   System.out.println(element.getText());
  }
 
  action.moveToElement(about).build().perform();//MouseOver of Menu
  driver.findElement(By.xpath("//*[@id='menu']/ul/li[2]/ul/li[1]/a")).click(); //Clicking Sub Menu
  Thread.sleep(3000);
  elements = driver.findElements(By.xpath(".//*[@id='menu']/ul/li[2]/ul/li/a"));
  for (WebElement element : elements) {
   System.out.println(element.getText());
  }
 
  action.moveToElement(contact).build().perform();//MouseOver of Menu
  driver.findElement(By.xpath("//*[@id='menu']/ul/li[3]/ul/li[1]/a")).click(); //Clicking Sub Menu
  Thread.sleep(3000);
  elements = driver.findElements(By.xpath(".//*[@id='menu']/ul/li[3]/ul/li/a"));
  for (WebElement element : elements) {
   System.out.println(element.getText());
  }
 }
}

Clicking on CSS Drop Down sub Menu using Selenium WebDriver

Purpose: Clicking on CSS Drop Down sub Menu using Selenium WebDriver

Some times we encounter to test different types of Web Sites which have some dynamic features and automating such features are little bit difficult. One of such example is CSS Drop Down Menus & Sub-menus.

Following code will help to handle CSS Drop Down Menus & Sub-menus:

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;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class DropDownCSSMenu {
 public String baseURL = "http://demo.lateralcode.com/css-drop-down-menus/";
 public WebDriver driver = new FirefoxDriver();
 public Actions action = new Actions(driver);

 @BeforeTest
 public void launchBrowser()
 {
  driver.get(baseURL);
 }

 @AfterTest
 public void closeBrowser()
 {
  driver.quit();
 }

 @Test
 public void test() throws InterruptedException
 {
  WebElement home = driver.findElement(By.linkText("Home"));
  WebElement about = driver.findElement(By.linkText("About"));
  WebElement contact = driver.findElement(By.linkText("Contact"));
 
  action.moveToElement(home).build().perform();//MouseOver of Menu
  driver.findElement(By.xpath("//*[@id='menu']/ul/li[1]/ul/li[1]/a")).click(); //Clicking Sub Menu
  Thread.sleep(3000);
 
  action.moveToElement(about).build().perform();//MouseOver of Menu
  driver.findElement(By.xpath("//*[@id='menu']/ul/li[2]/ul/li[1]/a")).click(); //Clicking Sub Menu
  Thread.sleep(3000);
 
  action.moveToElement(contact).build().perform();//MouseOver of Menu
  driver.findElement(By.xpath("//*[@id='menu']/ul/li[3]/ul/li[1]/a")).click(); //Clicking Sub Menu
  Thread.sleep(3000);
 }
}

Tuesday 17 September 2013

Executing Sequence of Selenium Test Cases in a Cusomized Sequence

Purpose: Executing Sequence of Selenium WebDriver Test Cases in a Cusomized Sequence

While automating any application we come across a situation where we need to execute multiple test cases in a particular sequence. But when it comes to execute the test cases they will execute randomly. In order to execute the test cases in our pre requisite order we need to pass a parameter to @Test method priority and a value(Lower priorities will be scheduled first).

Following code will be useful to accomplish the requirement:
 
 import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class OrderOfTestCase {

 public String baseURL = "http://www.google.com";
 public WebDriver driver = new FirefoxDriver();

 @BeforeTest
 public void launchBrowser()
 {
  driver.get(baseURL);
 }

 @AfterTest
 public void closeBrowser()
 {
  driver.quit();
 }

 @BeforeMethod
 public void getTitle()
 {
  System.out.println(driver.getTitle());
 }
 @AfterMethod
 public void goToPreviousPage()
 {
  driver.navigate().back();
 }

 @Test(priority = 0)
 public void images() throws InterruptedException
 {
  driver.findElement(By.linkText("Images")).click();
  Thread.sleep(3000);
  System.out.println(driver.getTitle());
 }

 @Test(priority = 1)
 public void maps() throws InterruptedException
 {
  driver.findElement(By.linkText("Maps")).click();
  Thread.sleep(3000);
  System.out.println(driver.getTitle());
 }

 @Test(priority = 2)
 public void mail() throws InterruptedException
 {
  driver.findElement(By.linkText("Gmail")).click();
  Thread.sleep(3000);
  System.out.println(driver.getTitle());
 }
}

Monday 16 September 2013

Extracting ZIP file programatically with the help of Java

Purpose: Extracting ZIP file programatically with the help of Java

Some time we may need to extract zip file and read the contents. Following code will help how to extract .zip files. I collected this program form some blog while searching and I want to share this to all through my blog.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class FileUnZip {
 public static void main(String[] args)
 {
  unzip("D://LatestSample.zip", "D://tmp");
  System.out.println("Unzip Completed");
 }

 public static void unzip(String zipFile,String outputPath){
  
        if(outputPath == null)
            outputPath = "";
        else
            outputPath+=File.separator;
        System.out.println(outputPath+=File.separator);
        // 1.0 Create output directory
        File outputDirectory = new File(outputPath);
        if(outputDirectory.exists())
            outputDirectory.delete();
        outputDirectory.mkdir();
        // 2.0 Unzip (create folders & copy files)
        try {
            // 2.1 Get zip input stream
            ZipInputStream zip = new ZipInputStream(new FileInputStream(zipFile));
            ZipEntry entry = null;
            int len;
            byte[] buffer = new byte[1024];
            // 2.2 Go over each entry "file/folder" in zip file
            while((entry = zip.getNextEntry()) != null){
                if(!entry.isDirectory()){
                    System.out.println("-"+entry.getName());                       
                    // create a new file
                    File file = new File(outputPath +entry.getName());
                    // create file parent directory if does not exist
                    if(!new File(file.getParent()).exists())
                        new File(file.getParent()).mkdirs();
                    // get new file output stream
                    FileOutputStream fos = new FileOutputStream(file);
                    // copy bytes
                    while ((len = zip.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                    fos.close();
                }
                zip.close();
            }
        }catch (FileNotFoundException e) {
                e.printStackTrace();
        } catch (IOException e) {
                e.printStackTrace();
        }
 }
}

Wednesday 11 September 2013

Adding An Image to Word programatically using Java

Purpose: Adding An Image to Word programatically using Java

Following Code will allow to add an Image to a Word file using Java from local or web based source.


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import word.api.interfaces.IDocument;
import word.w2004.Document2004;
import word.w2004.elements.BreakLine;
import word.w2004.elements.Image;
import word.w2004.elements.Paragraph;
public class AddImageToWord
{
    public static void main(String[] args) throws Exception
    {
     String img = "";
      IDocument doc = new Document2004();
      doc.addEle(Paragraph.with("Image from Web URL:").create());
      doc.addEle(new BreakLine(2)); //Add two break lines
      img = Image.from_WEB_URL("http://www.google.com/images/logos/ps_logo2.png").setHeight("100").setWidth("300").create().getContent();
      doc.addEle(img);
      doc.addEle(new BreakLine(2)); //Add two break lines
      doc.addEle(Paragraph.with("Image from Hard Disk:").create());
      doc.addEle(new BreakLine(2)); //Add two break lines
      String wh = Image.from_FULL_LOCAL_PATHL("D://Screen.png").getOriginalWidthHeight();
      String[] temp = wh.split("#");
      System.out.println(temp[0]);
      System.out.println(temp[1]);
      img = Image.from_FULL_LOCAL_PATHL("D://Screen.png").setHeight("300").setWidth("500").create().getContent();
      doc.addEle(img);
     
      File fileObj = new File("D://Java2word_allInOne.doc");
      PrintWriter writer = null;
      try {
          writer = new PrintWriter(fileObj);
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      }
      String myWord = doc.getContent();
      writer.println(myWord);
      writer.close();
    }
}


 

Tuesday 10 September 2013

How to add text to a word file using Java

Purpose: How to add text to a word file using Java


Following code will help you to Add text to a Word file programatically.

import java.io.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import java.io.FileOutputStream;
public class AddToWord
{
    public static void main(String[] args) throws IOException, InvalidFormatException
    {
        XWPFDocument document = new XWPFDocument();
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText("Sample Text to add a word file programatically");
        run.setFontSize(33);
        FileOutputStream out = new FileOutputStream("Success.doc");
        document.write(out);
        out.close();
    }
}

Generating previous day's Date using Java

Purpose: Generating previous day's Date using Java


Some times we may need to use date in different situations in different applications dynamically. That is very simple and we can use the methods of Date/Calender class. But some times we may need to capture previous day's date.

Following code will be useful to capture previous day's date.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class PreviousDate {
 public static void main(String[] args)
 {
//     Selecting Previous Date --- Start
    
     DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
     Date date = new Date();
     Calendar cal = new GregorianCalendar();
     cal.setTime(date);
     cal.add(Calendar.DAY_OF_YEAR,-1);
     Date oneDayBefore= cal.getTime();
     System.out.println();
     System.out.println("Previous Day's Date in dd/mm/yyyy format: "+dateFormat.format(oneDayBefore).toString());
//     Selecting Previous Date --- End
 }
}
 

Monday 9 September 2013

Capturing an Element Screenshot using Selenium Webdriver

Purpose: Capturing an Element Screenshot using Selenium Webdriver

Following Code will help to capture a particular element form a Webpage.

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class CaptureElement {
 static WebDriver driver;
 // Browser startup
 @BeforeClass
 public void setup() {
  driver = new FirefoxDriver();
 }

 @Test
 public void gomezTest() throws InterruptedException, IOException {
  // Capturing Required Element Screen shot
  driver.get("http://www.google.com");
  WebElement ele = driver.findElement(By.id("hplogo"));  
  try
  {
  File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
  BufferedImage  fullImg = ImageIO.read(screenshot);
  //Get the location of element on the page
  Point point = ele.getLocation();
  //Get width and height of the element
  int eleWidth = ele.getSize().getWidth();
  int eleHeight = ele.getSize().getHeight();
  //Crop the entire page screenshot to get only element screenshot
  BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight);
  ImageIO.write(eleScreenshot, "png", screenshot);
  //Copy the element screenshot to disk
  FileUtils.copyFile(screenshot, new File("GoogleLogo_screenshot.png"));
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }
 @AfterClass
 public void tear() {
  driver.close();
 }

Capturing Entire Page Screenshot using Selenium Webdriver

Purpose: Capturing Entire Page Screenshot using Selenium Webdriver

Following code will help to take the screenshot entire page of any webpage.

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TakeScreenshot {
 static WebDriver driver;
 // Browser startup
 @BeforeClass
 public void setup() {
  driver = new FirefoxDriver();
 }
 @Test
 public void gomezTest() throws InterruptedException, IOException {
  // Capturing Screen shot
  driver.get("http://www.google.com");
  //Get entire page screenshot
  try
  {
   File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

  //Copy the element screenshot to disk
  FileUtils.copyFile(screenshotFile, new File("\\GoogleLogo_screenshot.png"));
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }
 @AfterClass
 public void tear() {
  driver.close();
 }
}
 

Saturday 18 May 2013

Automation Testing for Android Mobile Web Applications & Steps to setup environment

Purpose: Automation Testing for Android Mobile Web Applications & Steps to setup environment
Introduction:

Android WebDriver allows to run automated end-to-end tests that ensure your site works correctly when viewed from the Android browser. Android WebDriver supports all core WebDriver APIs, and in addition to that it supports mobile spacific and HTML5 APIs. Android WebDriver models many user interactions such as finger taps, flicks, finger scrolls and long presses. It can rotate the display and interact with HTML5 features such as local storage, session storage and application cache.

The current apk will only work with Gingerbread (2.3.x), Honeycomb (3.x), Ice Cream Sandwich (4.0.x) and later.
  • Note that there is an emulator bug on Gingerbread that might cause WebDriver to crash.

Install the Android SDK:

Download the Android SDK, and unpack it to ~/android_sdk/. NOTE: The location of the Android SDK must exist in ../android_sdk, relative to the directory containing the Selenium repository.

Android WebDriver test can run on emulators or real devices for phone and tablets.

Setup Emulator

To create an emulator, you can use the graphical interface provided by the Android SDK, or the command line. Below are instructions for using the command line.

First, let's create an Android Virtual Device (AVD):

$cd ~/android_sdk/tools/
$./android create avd -n my_android -t 12 -c 100M


-n: specifies the name of the AVD.
-t: specifies the platform target. For an exhaustive list of targets, run:

./android list targets

Make sure the target level you selected corresponds to a supported SDK platform.
-c: specifies the SD card storage space.
When prompted "Do you wish to create a custom hardware profile [no]" enter "no".

Now, start the emulator. This can take a while, but take a look at the FAQ below for tips on how to improve performance of the emulator.

$./emulator -avd my_android &

Setup the Device

Simply connect your Android device through USB to your machine.

Using the Remote Server

This approach has a client and a server component. The client consists of your typical Junit tests that you can run from your favorite IDE or through the command line. The server is an Android application that contains an HTTP server. When you run the tests, each WebDriver command will make a RESTful HTTP request to the server using JSON according to a well defined protocol. The remote server will delegate the request to Android WebDriver, and will then return a response.

Install the WebDriver APK

Every device or emulator has a serial ID. Run this command to get the serial ID of the device or emulator you want to use:

$~/android_sdk/platform-tools/adb devices

Download the Android server from http://code.google.com/p/selenium/downloads/list. To install the application do:

$./adb -s <serialId> -e install -r  android-server.apk

Make sure you are allowing installation of application not coming from Android Market. Go to Settings -> Applications, and check "Unknown Sources".
Start the Android WebDriver application through the UI of the device or by running this command:

$./adb -s <serialId> shell am start -a android.intent.action.MAIN -n org.openqa.selenium.android.app/.MainActivity

Now we need to setup the port forwarding in order to forward traffic from the host machine to the emulator. In a terminal type:

$./adb -s <serialId> forward tcp:8080 tcp:8080

This will make the android server available at http://localhost:8080/wd/hub from the host machine. You're now ready to run the tests. Let's take a look at some code.

Run the Tests

import junit.framework.TestCase;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.android.AndroidDriver;
public class OneTest extends TestCase {
  public void testGoogle() throws Exception {
    WebDriver driver = new AndroidDriver();
   
    // And now use this to visit Google
    driver.get("http://www.google.com");
   
    // Find the text input element by its name
    WebElement element = driver.findElement(By.name("q"));
   
    // Enter something to search for
    element.sendKeys("Cheese!");
   
    // Now submit the form. WebDriver will find the form for us from the element
    element.submit();
   
    // Check the title of the page
    System.out.println("Page title is: " + driver.getTitle());
    driver.quit();
  }
}

To compile and run this example you will need the selenium-java-X.zip (client side piece of selenium). Download the selenium-java-X.zip from our download page, unzip and include all jars in your IDE project. For Eclipse, right click on project -> Build Path -> Configure Build Path -> Libraries -> Add External Jars

Hope this will be useful for steup and test your application under Android.

Tuesday 23 April 2013

Selecting any date from JQuery Date Picker using Selenium Web Driver

Purpose: Selecting any date from JQuery Date Picker using Selenium Web Driver

Automating JQuery Date Picker is not as easy as selecting Date Month Year select options. Following Selenium Web Driver code will help and provide basic logic to automate different JQuery Date Pickers.

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
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.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class JQueryDatePicket {
 WebDriver driver;
 WebElement dateWidget;
 List<WebElement> rows;
 List<WebElement> columns;
 List<String> list = Arrays.asList("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
 // Expected Date, Month and Year
 int expMonth;
 int expYear;
 String expDate = null;
 // Calendar Month and Year
 String calMonth = null;
 String calYear = null;
 boolean dateNotFound;

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

 @Test
 public void testJQueryDatePicket() throws InterruptedException{

  driver.get("http://jqueryui.com/datepicker/");
  driver.switchTo().frame(0);
  driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
  //Click on textbox of Date so that datepicker will appear
  driver.findElement(By.id("datepicker")).click();
  dateNotFound = true;
  expMonth= 3;
  expYear = 2015;
  expDate = "12";
  while(dateNotFound)
  {
  
   calMonth = driver.findElement(By.className("ui-datepicker-month")).getText();
   calYear = driver.findElement(By.className("ui-datepicker-year")).getText();
   if(list.indexOf(calMonth)+1 == expMonth && (expYear == Integer.parseInt(calYear)))
   {
    selectDate(expDate);
    dateNotFound = false;
   }
   else if(list.indexOf(calMonth)+1 < expMonth && (expYear == Integer.parseInt(calYear)) || expYear > Integer.parseInt(calYear))
   {
    driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[2]/span")).click();
   }
   else if(list.indexOf(calMonth)+1 > expMonth && (expYear == Integer.parseInt(calYear)) || expYear < Integer.parseInt(calYear))
   {
    driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[1]/span")).click();
   }
  }
  Thread.sleep(3000);
 }
 public void selectDate(String date)
 {
 dateWidget = driver.findElement(By.id("ui-datepicker-div"));
 rows=dateWidget.findElements(By.tagName("tr"));
 columns=dateWidget.findElements(By.tagName("td"));

 for (WebElement cell: columns){
  //Selects Date
  if (cell.getText().equals(date)){
   cell.findElement(By.linkText(date)).click();
   break;
  }
 }
 }

 @AfterTest
 public void tearDown()
 {
  driver.quit();
 }
}

Monday 8 April 2013

Writing simple Data Driven Framework scripts using TestNG

Purpose: Writing simple Selenium Scripts by implementing Data Driven Framework using TestNG

Data Driven Framework scripts means executing a set of steps with multiple sets of data. Selenium is not have any default way of implementing but by using TestNG support we can implement it successfully.

Step 1: JXL API Jar - We can download it form the following URL
http://sourceforge.net/projects/jxls/files/ and download latest version

Step 2: Prepare Data Source - Open an excel and prepare data source as shown below


In this example we are discussing reading inputs from an excel sheet and writing the results in reports sheet.

Step 3: Following example will demonstrate how to access from an excel sheet and how to write the results into an excel sheet.

package com.google.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class GMail{
 private WebDriver driver;
 private String baseURL;
 private FileInputStream fi;
 private Sheet s;
 private Workbook wb;

 @BeforeClass
 public void setup() throws BiffException, IOException
 {
  driver = new FirefoxDriver();
  baseURL = "http://www.gmail.com";
  fi = new FileInputStream("TestDate\\Book1.xls");
  wb = Workbook.getWorkbook(fi);
  s = wb.getSheet(0);
 }

 @AfterClass
 public void teardown()
 {
  driver.quit();
 }
 @Test
 public void testGmail() throws InterruptedException
 {
  for(int row=0; row <s.getRows();row++)
  {
    String username = s.getCell(0, row).getContents();
    System.out.println("Username "+username);
    driver.get(baseURL);
    driver.findElement(By.name("Email")).sendKeys(username);
    String password= s.getCell(1, row).getContents();
    System.out.println("Password "+password);
    driver.findElement(By.name("Passwd")).sendKeys(password);
    Thread.sleep(10000);
    Thread.sleep(30000);
    writeExcel(0, 0, "Passes");
  }
 }

public void writeExcel(int a, int b, String text) {
    try {
        File excelFile = new File("TestDate\\Results.xls");
        WritableWorkbook book;
        WritableSheet sheet;
        Workbook existingBook = null;
        if (!excelFile.exists()) {
            book = Workbook.createWorkbook(excelFile);
            sheet = book.createSheet("TESTRESULTS", 0);
        } else {
            existingBook = Workbook.getWorkbook(excelFile);
            book = Workbook.createWorkbook(excelFile, existingBook);
            sheet = book.getSheet("TESTRESULTS");
        }
        Label i = new Label(a, b, text);
        sheet.addCell(i);
        book.write();
        book.close();
        if (existingBook != null)
            existingBook.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}



















 

Setting up Eclipse Environment for Selenium

Purpose: Setting up Eclipse IDE environment to Run Selenium Script

Following are the steps to setup successful Selenium environment for Eclipse IDE

In order to Setup, we need Java, Eclipse IDE, Selenium Webdriver, TestNG.

Step 1: Download Java and install if not installed. Visit the following URL and download JDK
URL: http://www.oracle.com/technetwork/java/javase/downloads/index.html

Step 2: Download Eclipse IED and it not require ant install. Extract and open. Visit for following URL and download Eclipse

URL: http://www.eclipse.org/downloads/ download Eclipse IDE for Java EE Developers 32bit version

Step 3: Download Selenium Webdriver and build the path. Visit the following URL and download required Selenium Softwares

URL: http://selenium.googlecode.com/files/selenium-server-standalone-2.31.0.jar

Step 4: Install TestNG for Eclipse

Select Help /  Install New Software /
Click on Add
Enter Any relevent Name for Name Field
Enter URL for Eclipse 3.4 and above, enter http://beust.com/eclipse/
For Eclipse 3.3 and below, enter http://beust.com/eclipse1/
Select TestNG Software, Click Next and Install

Step 5: Create New Java Project and Create New TestNG file
Step 6: Right Click on Project > Build Path > Configure Build Path > Click Libraries > Click Add External Jars. Select the location of Selenium Webdriver and add the Selenuium .Jar file to Eclipse IDE Environment.

Step 6: Write the script and execute. Hope it will lanch application successfully.

Capturing all Links in a page, filtering and visiting filtered pages.

Purpose: Capturing all Links in a page, filtering and visiting filtered pages.


In general while testing any application we are facing a situation where we need to visit specific link available on the Web Page. The Following script help floks how to handle it.

In the following example, I am going to visit 'www.google.com', captures all the links available on the page, filter the required link and visit that link page.

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;

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

  WebDriver driver = new FirefoxDriver();
  driver.get("http://www.tata.com/");
  driver.manage().window().maximize();
//  Extract all links from the webpage using selenium webdriver
  List<WebElement> all_links_webpage = driver.findElements(By.tagName("a"));

//  Print total no of links on the webpage
  System.out.println("Print total no of links on the webpage---------------------------------------------");
  System.out.println(all_links_webpage.size());

//  Filter the Link and visit that link
  System.out.println("Print Links------------------------------------------------------------------------");
  for(int i=0;i<all_links_webpage.size();i++)
  {
   Thread.sleep(1000);
   if(all_links_webpage.get(i).getText().toLowerCase().contains("contact"))
   {
    System.out.println("Search Resutl found");
   String link = all_links_webpage.get(i).getAttribute("href");
   driver.navigate().to(link);
   Thread.sleep(3000);
   break;
   }
  }
 driver.quit();
 }
}

How to Run Webdriver Script under Internet Explorer and Google Chrome

Purpose: How to Run Webdriver Script for Internet Explorer and Google Chrome

Running Webdriver script for Internet Explorer & Chrome is not as same as working with Firefox browser. Following are the steps to Run:

Step 1: In order to run, we need to download IE Driver & Chrome Driver and we can download from https://code.google.com/p/selenium/downloads/detail?name=IEDriverServer_Win32_2.31.0.zip
https://code.google.com/p/chromedriver/downloads/list

Step 2: Include the respective drivers in to the Path

Step 3: Set the System property using the following Command which takes two parameters Driver and location of the driver.

System.setProperty("webdriver.ie.driver", "Drivers\\IEDriverServer.exe");

Step 4: Now create an Driver Object for IE using the following command

driver = new InternetExplorerDriver();

Once we start running the script Internet Explorer will open and execute script.

Following is the sample code for IE and kept commented code for Google Chrome

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class DriversExample{
private static InternetExplorerDriver driver;
//private static ChromeDriver driver;
@BeforeClass
 public void beforeClass()
 {
  System.setProperty("webdriver.ie.driver", "Drivers\\IEDriverServer.exe");
  driver = new InternetExplorerDriver();
//  System.setProperty("webdriver.chrome.driver", "Drivers\\chromedriver.exe");
//  driver = new ChromeDriver();
  }
@Test
 public void testDrivers() throws Exception
 {
  driver.get("http://www.google.com");
  Thread.sleep(3000);
 }
@AfterClass
 public void afterClass()
 {
  driver.close();
 }
}

Monday 1 April 2013

Capturing all Links on a Web Page and visiting those links using Web Driver

Purpose: Capturing all Links on a Web Page and visiting those links

In general while testing any application we are facing a situation where we need to visit each link available on the Web Page. The Following script help floks how to handle it.

In the following example, I am going to visit 'www.google.com', captures all the links available on the page, visiting each link and coming back to home page.



importjava.util.List;
importorg.openqa.selenium.By;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.firefox.FirefoxDriver;

public class Links {

private static String homeWindow = null;
private static String[] links = null;
private static int linksCount = 0;

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

WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
// Fllowing instruction extract all links from the webpage using selenium webdriver
List<WebElement> all_links_webpage = driver.findElements(By.tagName("a"));
// Print total no of links on the webpage
System.out.println("Print total no of links on the webpage----------------------------------------------------");
linksCount = all_links_webpage.size();
System.out.println(linksCount);
links= new String[linksCount];// Following instruction stores each link and Prints on console
System.out.println("Print Links-----------------------------------------------------------------------------------");

for(int i=0;i<linksCount;i++)
{
links[i] = all_links_webpage.get(i).getAttribute("href");
System.out.println(all_links_webpage.get(i).getAttribute("href"));
}
// Following instruction Return an opaque handle to this window that uniquely identifies it within this driver instance.
// This can be used to switch to this window at a later date
homeWindow = driver.getWindowHandle().toString();
// Visiting Each Link in on the Page

System.
out.println("Visiting Each Links------------------------------------------------------------------------");

for(int i=0;i<linksCount;i++)
{
driver.navigate().to(
links[i]);
Thread.sleep(3000);
driver.switchTo().window(
homeWindow);
}
driver.quit();
}
}

Tuesday 19 March 2013

Maximizing Browser Window using Selenium Rc and Web Driver

Purpose: Maximizing Browser window using Selenium RC and Web Driver

When ever we are opening Web Browser using Selenium RC and Web Driver, it will open in Resized state. But that will not give complete view of the Browser conten. In order to maximize the the window we need to use two different methods in RC and Web Driver.

Maximizing the Browser Window using RC

Once you started the Browser use the following Selenium RC command to maximize the Browser Window
(browser is the object of my DefaultSelenium Class)

browser.windowMaximize();

Maximizing the Browser Window using Web Driver:

It is not as same as RC in Web Driver. We need to use the following command

( driver is the Object of Respective Browser Driver Class )

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

Unsupported Major/Minor Version issue while executing Selenium Scripts / Java Programs using Eclipse IDE

Purpose: When ever we are executing Selenium Scripts / Java Program which is developed / written in some othere version than our version we will get the error "Java.lang.UnsupportedClassVersionError: .............................Unsupported major.minor version"

If you are executing the program using Console / Command Prompt, using additional parameter -source <version number>

For example, if your file name is VersionError.java and executing through Command Prompt use the following command to execute successfully:

javac -source 1.4 VersionError.java

The program will compile successfully.

If you are executing the code using Eclipse IDE follow the steps mentioned below:

Step 1: Click on 'Project' menu option and select 'Properties' submenu.



Step 2: Click on Project Facts from RNP and Select Java in RNP




Step 3: Select required version of Java and click on OK.

Now Run the application and the issue will be resolved.

Monday 25 February 2013

Switching between Windows using Selenium Webdriver

Purpose: Switching between Windows using Selenium Webdriver

We come across to handle switching b/w windows while accessing different webpages. Inroder to automate switching b/w windows, following steps will help you to write Selenium Webdriver Script with the help of Java

It is not as easy as handling with Selenium Rc. We can achive with the help of getWindowHandle() and switchTo().window() methods.

Following is the Selenium Webdriver with Java script to handle popup windows:


package com.webdriver;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SwitchWindow {

 public static void main(String[] args) throws Exception
 {
  FirefoxDriver driver = new FirefoxDriver();
  driver.get("http://www.quackit.com/html/codes/");
  // Return an opaque handle to this window that uniquely identifies it within this driver instance. This can be used to switch to this window at a later date
  String parentWindow = driver.getWindowHandle().toString();
  driver.findElement(By.linkText("Pop up windows")).click();
  Thread.sleep(3000);
  assert(driver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*Example HTML Popup Window Code:[\\s\\S]*$"));
    driver.findElement(By.linkText("Open a popup window")).click();
    // to switch control to the new popup window by name
    driver.switchTo().window("popUpWindow");
    assert(driver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*Copy/Paste HTML Codes[\\s\\S]*$"));
    // closing the popup window
  driver.close();
  // to switch control from popup window to another window, here parent window
  driver.switchTo().window(parentWindow);
  assert(driver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*Example HTML Popup Window Code:[\\s\\S]*$"));
  driver.close();
 }
}

// Code for TestNG

package com.webdriver;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
public class SwitchWindow {
 FirefoxDriver driver;
  @Test
  public void testSwitchWindow() {
   driver.get("http://www.quackit.com/html/codes/");
   // Return an opaque handle to this window that uniquely identifies it within this driver instance. This can be used to switch to this window at a later date
   String parentWindow = driver.getWindowHandle();
   assert(driver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*HTML Codes - Free[\\s\\S]*$"));
   assert(driver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*Pop up windows[\\s\\S]*$"));
   driver.findElement(By.linkText("Pop up windows")).click();
   assert(driver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*Open a popup window[\\s\\S]*$"));
   driver.findElement(By.linkText("Open a popup window")).click();
   // to switch control to the new popup window by name
   driver.switchTo().window("popUpWindow");
   assert(driver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*Copy/Paste HTML Codes[\\s\\S]*$"));
   // closing the popup window
   driver.close();
   // to switch control from popup window to another window, here parent window
   driver.switchTo().window(parentWindow);
   assert(driver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*Open a popup window[\\s\\S]*$"));
  }
  @BeforeClass
  public void beforeClass() {
   driver = new FirefoxDriver();
   driver.manage().window().maximize();
  }
  @AfterClass
  public void afterClass() {
   driver.close();
  }
}