Automation Using Selenium Webdriver

Wednesday, 19 October 2016

@ TestNG Annotations & Uses

TestNG Annotations

@BeforeSuite: The annotate method will be run before all tests in this suite have run.
@AfterSuite: The annotated method will be run after all tests in this suite have run.
@BeforeClass: The annotated method will be run before the first test method in the current class is
 invoked.
@AfterClass: The annotated method will be run after all the test methods in the current class have been run.
@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the tag is run.
@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the tag have run.
@BeforeMethod: The annotated method will be run before each test method.
@Test: The annotated method is a part of a test case.
@AfterMethod: The annotated method will be run after each test method.
@DataProvider: The annotated method provides data to the @Test methods.
The annotated method returns an Object [][].
@BeforeGroups: The list of groups that this configuration method will run before.
This method is guaranteed to run shortly before the first test method that belongs to any of these
groups is invoked.
@AfterGroups: The list of groups that this configuration method will run after.
 This method is guaranteed to run shortly after the last test method that belongs to any of these
groups is invoked.

alwaysRun----> For before methods (beforeSuite, beforeTest, beforeTestClass and                     beforeTestMethod,but not beforeGroups): If set to true, this configuration method will be run regardless of what groups it belongs to. For after methods (afterSuite, afterClass, ...): If set to true, this configuration method will be runeven if one or more methods invoked previously failed or was skipped.
dependsOnGroups----> The list of groups this method depends on.
dependsOnMethods----> The list of methods this method depends on.
enabled                  -----> Whether methods on this class/method are enabled.
groups                 ------>The list of groups this class/method belongs to.
inheritGroups      ------->If true, this method will belong to groups specified in the @Test annotation
at the class level.

package testng;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class TestNGAnnotations {

 @BeforeSuite
 public void instantiate() {
  System.out.println("Instantiate Object");
 }

 @BeforeTest
 public void dataBaseConnection() {
  System.out.println("Database Connected");
 }

 @BeforeMethod
 public void BeforeMethod() {
  System.out.println("Run before each Test Case.");
 }

 @Test
 public void testCase1() {
  System.out.println("First Test Case Result..... ");
 }

 @Test
 public void testCase2() {
  System.out.println("Second Test Case Result.... ");
 }

 @AfterMethod
 public void AfterMethod() {
  System.out.println("Run after each Test Case");
 }

 @AfterTest
 public void dataBaseDisconnection() {
  System.out.println("Database Disconnected");
 }

 @AfterSuite
 public void destory() {
  System.out.println("Destory Object");
 }
}
Create testng.xml:

testng.xml: Right click on Project --> TestNG --> Convert to TestNG.

<!--?xml version="1.0" encoding="UTF-8"?-->

<suite name="Suite" parallel="none">
  <test name="Test">
    <classes>
      <class name="testng.TestNGAnnotations">
    </class></classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->
Execute TestNG:
Right click on testng.xml --> Run As --> TestNG Suite OR Right click on java file -->
 Run As --> TestNG Test

OUTPUT:


Download file using Selenium WebDriver with AutoIt and Sikuli

Download file using Selenium WebDriver with AutoItand Sikuli
Selenium can not handle the Download file window. We can use third party tools to handle download
file window. Some of the tools are AutoIT and Sikuli.

AutoIT: Save the below script with extension as download_file.au3 and compile it then it will generatedownload_file.exe file.

Local $pathToSave=$CmdLine[1]
Local $windHandle=WinGetHandle("[Class:IEFrame]", "")
Local $winTitle = "[HANDLE:" & $windHandle & "]";
;get coordinates of default HWND
Local $ctlText=ControlGetPos ($winTitle, "", "[Class:DirectUIHWND;INSTANCE:1]")

; wait till the notification bar is displayed
Local $color= PixelGetColor ($ctlText[0],$ctlText[1])
while $color <> 0
sleep(500)
$ctlText=ControlGetPos ($winTitle, "", "[Class:DirectUIHWND;INSTANCE:1]")
$color= PixelGetColor ($ctlText[0],$ctlText[1])

wend
; Select save as option
WinActivate ($winTitle, "")
Send("{F6}")
sleep(500)
Send("{TAB}")
sleep(500)
Send("{DOWN}")
sleep(500)
Send("a")

WinWait("Save As")
; activate Save As window
WinActivate("Save As")
; path to save the file is passed as command line arugment
ControlFocus("Save As","","[CLASS:Edit;INSTANCE:1]")
Send($pathToSave)
sleep(500)
;click on save button
ControlClick("Save As","","[TEXT:&Save]")

; wait till the download completes
Local $sAttribute = FileGetAttrib($pathToSave);
while $sAttribute = ""
sleep(500)
$sAttribute = FileGetAttrib($pathToSave)
wend
sleep(2000)
;close the notification bar
WinActivate ($winTitle, "")
Send("{F6}")
sleep(300)
Send("{TAB}")
sleep(300)
Send("{TAB}")
sleep(300)
Send("{TAB}")
sleep(300)
Send("{ENTER}")

import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class DownloadFile_IE_AutoIT {

 public static void main(String[] args) throws InterruptedException {
  System.setProperty("webdriver.ie.driver",System.getProperty("user.dir")+"\\IEDriver.exe");
  WebDriver driver = new InternetExplorerDriver();
  driver.manage().window().maximize();
  driver.get("http://www.seleniumhq.org/download/");
  driver.findElement(By.xpath("//*[@id='mainContent']/p[9]/a[2]")).sendKeys(Keys.ENTER);
  try {
   String path="E:\\AutoIT\\test232";
   String file="E:\\AutoIT\\download_file.exe"+" "+path;
         Runtime.getRuntime().exec(file);
     } catch (IOException e) {
   e.printStackTrace();
  }
 }
}
AutoIT: Download AutoIT from http://www.autoitscript.com/site/autoit/downloads/
Once you install AutoIT in system. Write a autoit script to handle the authentication window.
WinWaitActive("Windows Security")
Send("username")
Send("{TAB}")
Send("password")
Send("{ENTER}")
Save this file as “auth.au3"
Right click on the file and chose “Compile Script (x86)” option and it will make “auth.exe”
Now write the sample java code to use it
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class WinAuthentication_Autoit {

 public static void main(String[] args) {
  System.setProperty("webdriver.ie.driver",System.getProperty("user.dir")+"\\IEDriver.exe");
  WebDriver driver = new InternetExplorerDriver();
  driver.get("http://codesorcery.net/old/authentication/secret/");
  try {
   Runtime.getRuntime().exec("E:\\AutoIT\\Auth.exe");
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

How to verify element present or visible in selenium 2 (Selenium WebDriver)


Verify Element Present or Visible in Web Application Check
1.ispresent
2.isvisible
3.isenable
4.textpresent

in Selenium WebDrvier using Java

To check Element Present:

if(driver.findElements(By.xpath("value")).size() != 0){
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}

                  OR
if(driver.findElement(By.xpath("value"))!= null){
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}

To check Visible:

if( driver.findElement(By.cssSelector("a > font")).isDisplayed()){
System.out.println("Element is Visible");
}else{
System.out.println("Element is InVisible");
}


To check Enable:

if( driver.findElement(By.cssSelector("a > font")).isEnabled()){
System.out.println("Element is Enable");
}else{
System.out.println("Element is Disabled");
}

To check text present:

if(driver.getPageSource().contains("Text to check")){
System.out.println("Text is present");
}else{
System.out.println("Text is absent");
}

Tuesday, 18 October 2016

Selenium Tester Job Responsibilites

Selenium Tester Job Responsibilities

Job Responsibilities may vary from one company to another and one project to another, but I am covering this topic by considering several companies approaches.

Selenium Knowledge for Fresher or below 1 Year Experienced
 

• Basic Understanding of Functional and Regression Test Automation.

• Good knowledge on Selenium suite of Tools (Selenium IDE, Selenium RC, Selenium WebDriver and Selenium Grid).

• Knowledge of Java Programming (Data Types, Variables, Operators, Flow Control Statements, Methods (Built-in as well as User defined), Exception handling, File Handling, Excel file Operations, Database Operations and OOPS concepts).

• Good knowledge on Element Locators, Selenese Commands, WebDriver methods.

• Idea on Test Automation Framework implementation

• Ability to create and execute Test cases using Selenium IDE and Selenium Webdriver.


I) 1+ Years Experience in Test Automation using Selenium
 

• Understanding Test Requirements and analyzing the Application under Test(AUT).

• Generating Test Cases (Test Scripts) using Selenium Element locators and WebDriver Methods.

• Enhancing Test cases using Java programming.

• Debugging Test Cases and Fixing errors.

• Executing/Running Test Cases

• Defect Reporting & Tracking

• Test Reporting
--------------------------------------------------
II) 2+ years of Experience in Test Automation using Selenium
 

• Creating Test Automation Resources (Function Libraries etc...).

• Handling duplicate objects and dynamic objects using index property and Regular expressions.

• Collecting Test Data for Data Driven Testing.

• Creating Test Cases (Test Scripts) using Selenium Webdriver, Java and TestNG Annotations.

• Parameterization, Synchronization and define Test results.

• Debugging and Running Tests

• Analyzing Test Results

• Defect Reporting and Tracking using any Defect Management Tool.

• Test Reporting

• Modifying Tests and performing Re & Regression Testing.
--------------------------------------------------
III) 3+ years of Experience in Test Automation using Selenium
 

• Understanding and Analyzing the Application Under Test in terms of Object Identification.

• Creating Test scenarios and Collecting Test Data.

• Identifying end to end scenarios and code modularity.

• Implementing JUnit or TestNG Test Automation framework and developing automation infrastructure.

• Creating reusable components.

• Creating and enhancing Test Cases (Test Scripts) using Element locators, WebDriver methods, Java programming concepts and TestNG Annotations.

• Error Handling, Adding comments.

• Creating Data driven Tests and Running through framework.

• Cross Browser Testing (Executing test cases against various browsers like Mozilla Firefox, Google chrome, IE and Safari etc...).

• Parallel Test Execution.

• Defining and exporting Test Results.

• Analyzing Test Results and Reporting Defects.

• Tracking Defects and Select Test cases for Re & Regression Testing.

• Modifying Test Automation Resources and Maintenance of Resources.
--------------------------------------------------
IV) 4+ years of Experience in Test Automation using Selenium
 

• Selecting or Identifying areas/test cases for Automation.

• Designing & Implementing Test Automation Strategy.

• Creating Automation Test Plan and getting approvals.

• Choose selenium tools and Configuring Selenium Test Environment (Ex: Eclipse IDE, Java, Selenium WebDriver and TestNG etc...).

• Creating, Organizing, and managing Test Automation Resources.

• Creating, Enhancing, debugging and Running Test Cases.

• Organizing, monitoring defect management process.

• Handling changes and conducting Regression Testing.

• Finding solutions for Object Identification issues and error handling issues.

• Co-coordinating Test team members and Development team in order to resolve the issues.

• Interacting with client side people to solve issues and update status.
--------------------------------------------------
Focus on:
 
> Test Automation Life Cycle.

> Verify Web Elements(Objects) using Firebug and Firepath Plug ins in Mozilla Firefox browser, if it IE or Google Chrome use built-in developer tools(Shortcut key F12).

> Create Test Cases using Element locators and Selenium WebDriver Methods.

> Enhance Test cases using Java Programming and JUnit / TestNG Annotations.




Alerts Popups, Confirmations And Prompts Handle in Selenium Webdriver

Alert Popup
Generally alert message popup display on page of software web application with alert text and Ok button as shown In bellow given Image.

Confirmation Popup
Confirmation popup displays on page of software web application with confirmation text, 
Ok and Cancel button as shown In bellow given Image.



Prompt Popup
Prompts will have prompt text, Input text box, Ok and Cancel buttons.






Selenium webdriver software testing tool has Its own Alert Interface to handleall above different popups.Alert Interface has different methods like accept(), dismiss(), getText(),
 sendKeys(java.lang.String keysToSend) and we can use all these methods to perform different 
actions on popups.


VIEW WEBDRIVER EXAMPLES STEP BY STEP

Look at the bellow given simple example of handling alerts, confirmations and prompts In 
selenium webdriver software automation testing tool. Bellow given example will perform different
 actions (Like click on Ok button, Click on cancel button, retrieve alert text, type text In prompt 
text box etc..)on all three kind of popups using different methods of Alert Interface.

Run bellow given example In eclipse with testng and observe the result.

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class unexpected_alert {
 WebDriver driver;

 @BeforeTest
 public void setup() throws Exception {
  driver =new FirefoxDriver();     
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
  driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
 }

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

 @Test
 public void Text() throws InterruptedException {
  //Alert Pop up Handling.
  driver.findElement(By.xpath("//input[@value='Show Me Alert']")).click();
  //To locate alert.
  Alert A1 = driver.switchTo().alert();
  //To read the text from alert popup.
  String Alert1 = A1.getText();
  System.out.println(Alert1);
  Thread.sleep(2000);
  //To accept/Click Ok on alert popup.
  A1.accept();
  
  //Confirmation Pop up Handling.
  driver.findElement(By.xpath("//button[@onclick='myFunction()']")).click();
  Alert A2 = driver.switchTo().alert();
  String Alert2 = A2.getText();
  System.out.println(Alert2);
  Thread.sleep(2000);
  //To click On cancel button of confirmation box.
  A2.dismiss();
  
  //Prompt Pop up Handling.
  driver.findElement(By.xpath("//button[contains(.,'Show Me Prompt')]")).click();
  Alert A3 = driver.switchTo().alert();
  String Alert3 = A3.getText();
  System.out.println(Alert3);
  //To type text In text box of prompt pop up.
  A3.sendKeys("This Is John");
  Thread.sleep(2000);
  A3.accept();  
 }
}

How to find broken links using Selenium WebDriver with Java


I want to verify broken links on a website and I am using this code:

package com.automation.test;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
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 Test {
    public static int invalidLink;
    String currentLink;
    String temp;
    public static void main(String[] args) throws IOException {
        // Launch The Browser
        WebDriver driver = new FirefoxDriver();
        // Enter Url
        driver.get("any web site");
        // Get all the links url
        List<WebElement> ele = driver.findElements(By.tagName("a"));
        System.out.println("size:" + ele.size());
        boolean isValid = false;
        for (int i = 0; i < ele.size(); i++) {
            // System.out.println(ele.get(i).getAttribute("href"));
            isValid = getResponseCode(ele.get(i).getAttribute("href"));
            if (isValid) {
                System.out.println("ValidLinks:"
                        + ele.get(i).getAttribute("href"));
            } else {
                System.out.println("InvalidLinks:"
                        + ele.get(i).getAttribute("href"));
            }
        }
    }
    public static boolean getResponseCode(String urlString) {
        boolean isValid = false;
        try {
            URL u = new URL(urlString);
            HttpURLConnection h = (HttpURLConnection) u.openConnection();
            h.setRequestMethod("GET");
            h.connect();
            System.out.println(h.getResponseCode());
            if (h.getResponseCode() != 404) {
                isValid = true;
            }
        } catch (Exception e) {
        }
        return isValid;
    }
}

Try the following piece of code another Method::

package com.automation.test;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
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 Test {
    public static int invalidLink;
    String currentLink;
    String temp;

    public static void main(String[] args) throws IOException {
        // Launch The Browser
        WebDriver driver = new FirefoxDriver();
        // Enter Url
        driver.get("any web site");

        // Get all the links url
        List<WebElement> ele = driver.findElements(By.tagName("a"));
        System.out.println("size:" + ele.size());
        boolean isValid = false;
        for (int i = 0; i < ele.size(); i++) {
            // System.out.println(ele.get(i).getAttribute("href"));
            isValid = getResponseCode(ele.get(i).getAttribute("href"));
            if (isValid) {
                System.out.println("ValidLinks:"
                        + ele.get(i).getAttribute("href"));
            } else {
                System.out.println("InvalidLinks:"
                        + ele.get(i).getAttribute("href"));
            }
        }
    }
    public static boolean getResponseCode(String urlString) {
        boolean isValid = false;
        try {
            URL u = new URL(urlString);
            HttpURLConnection h = (HttpURLConnection) u.openConnection();
            h.setRequestMethod("GET");
            h.connect();
            System.out.println(h.getResponseCode());
            if (h.getResponseCode() != 404) {
                isValid = true;
            }
        } catch (Exception e) {
        }
        return isValid;
    }
}
I have modified getResponseCode to return boolean values based on whether the url is valid(true) or invalid(false).
Hope this helps you




Functional Implementation in Selenium Webdriver Exp

Functional Implementation:
In this implementation we will split up the page on the basis of functionalities and will have the methods like LoginToGmailAsValidUser and LoginToGmailAsInvalidUser.

See the below code snippet::

public class GmailLoginPage
 {
  private final WebDriver driver;
//Page Object constructor which passes the driver context forward
   public LoginPage(WebDriver driver) {
      this.driver = driver;
  }
  By usernameloc = By.id("Email");
  By passwordloc = By.id("Passwd");
  By loginButtonloc = By.id("signIn");
 
  public HomePage LoginToGmailAsValidUser(String username, String password) 
{
 driver.findElement(usernameloc ).sendKeys(username);
driver.findElement(passwordloc ).sendKeys(password);
driver.findElement(loginButtonloc   ).click();
    return new InboxPage(driver) 
  }
  public GmailLoginPage LoginToGmailAsInvalidUser(String username, String password) {
 driver.findElement(usernameloc ).sendKeys(username);
 driver.findElement(passwordloc ).sendKeys(password);
 driver.findElement(loginButtonloc   ).click();
    return this;
  }
}
The benefit of this approach is that the page structure is completely abstracted from the test layer. For example an extra checkbox “stay signed in” has been added on the login page and it also needs to be selected while logging a user in. So we simply need to add the extra code to handle this checkbox in the same method of the page class and it will not have any impact on the test layer, as the tests will still call the same method to login.

Structural Implementation:

In this approach the page is divided structurally depending upon the number of elements on the page
which we need to interact with. See the below code snippet:
public class GmailLoginPage
 {
  private final WebDriver driver;
//Page Object constructor which passes the driver context forward
  public LoginPage(WebDriver driver) 
{
      this.driver = driver;
  }
  By usernameloc = By.id("Email");
  By passwordloc = By.id("Passwd");
  By loginButtonloc = By.id("signIn");
 
  public HomePage typeUsername(String username) 
{
    driver.findElement(usernameloc).sendKeys(username);
    return this;
  }
public HomePage typePassword(String password)
 {
   driver.findElement(passwordloc ).sendKeys(password);
    return this;
  }
public HomePage clickOnSignin(String password) 
{
  driver.findElement(loginButtonloc   ).click();
   return new InboxPage(driver) 
  }
}


Challenges in Implementing Page Object Model:

Page object model is a very effective design pattern provided it is implemented correctly. I would like to cover some 
complex scenarios.

Whenever any pageObject service (method) results in to a new page navigation, then that new page should be returned by the method. Let’s take the above example of Gmail login and as we know the method LoginToGmail() will lead us to the Inbox page so this should have a return type of InboxPage. See the below code:

public HomePage LoginToGmail(String username, String password)
 {
    driver.findElement(usernameloc).sendKeys(username);
  driver.findElement(passwordloc ).sendKeys(password);
  driver.findElement(loginButtonloc   ).click();
    return new InboxPage(driver) 
  }
GmailLoginPage loginPage = new GmailLoginPage (driver);
InboxPage = loginPage.LoginToGmail(“username”,”password”);