Automation Using Selenium Webdriver

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”);

@FindBy annotations Using in Java

@FndBy Annotations Using

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class LoginPage {
 
    @FindBy(id="loginInput") //method used to find WebElement, in that case Id
    WebElement loginTextbox;
 
    @FindBy(id="passwordInput")
    WebElement passwordTextBox;
 
    @FindBy(xpath="//form[@id='loginForm']/button(contains(., 'Login')") //method = xpath
    WebElement loginButton;
 
    public void login(String username, String password){
        // login method prepared according to Page Object Pattern
        loginTextbox.sendKeys(username);
        passwordTextBox.sendKeys(password);
        loginButton.click();
        // because WebElements were declared with @FindBy, we can use them without
        // driver.find() method
    }
}

And Tests class:

class Tests{
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        LoginPage loginPage = new LoginPage();
        PageFactory.initElements(driver, loginPage); //PageFactory is used to find elements with @FindBy specified
        loginPage.login("user", "pass");
    }
}

Yahoo mail sign out Code Selenium WebDriver

Code for yahoo mail sign out

FirefoxDriver driver = new FirefoxDriver();
driver.get("https://login.yahoo.com/config/login_verify2?.intl=ca&.src=ym");
driver.manage().window().maximize();

WebElement element = driver.findElement(By.id("username"));
element.sendKeys("myid@yahoo.com");

driver.findElement(By.id("passwd")).sendKeys("mypassword");
element.submit();
Thread.sleep(40000);

driver.findElement(By.linkText("Sign Out")).click();  
Thread.sleep(40);

Monday 17 October 2016

@DataProvider TestNG Real time Project Data-Driven Testing Example

 TestNG Selenium Data-Driven Testing Example
Suppose we want to do multiple searches in google by using our search method, we would want to pass in different search strings each time we call the method. In this example, I will demonstrate data-driven testing to do multiple searches in google.
We will modify our example further and introduce a parameter to our search method. Since we will be searching multiple times, we will keep the search method name generic, call it searchGoogle(). We will provide the data using a@DataProvider method called searchStrings() which returns “TestNG” and “Selenium” as the search keywords. The@Test annotation is modified to include searchGoogle as the dataProvider.

TestNGSeleniumDataDrivenSearchExample

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.support.ui.ExpectedCondition;

import org.openqa.selenium.support.ui.WebDriverWait;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;

import org.testng.annotations.AfterSuite;

import org.testng.annotations.BeforeClass;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;



@ContextConfiguration("driver_context.xml")

public class TestNGSeleniumDataDrivenSearchExample extends

        AbstractTestNGSpringContextTests {

    private WebDriver driver;



    @BeforeClass

    public void printBrowserUsed() {

        System.out.println("Driver used is: " + driver);

    }



    @Test(dataProvider = "searchStrings")

    public void searchGoogle(final String searchKey) {

        System.out.println("Search " + searchKey + " in google");

        driver.navigate().to("http://www.google.com");

        WebElement element = driver.findElement(By.name("q"));

        System.out.println("Enter " + searchKey);

        element.sendKeys(searchKey);

        System.out.println("submit");

        element.submit();

        (new WebDriverWait(driver, 10)).until(new ExpectedCondition() {

            public Boolean apply(WebDriver d) {

                return d.getTitle().toLowerCase()

                        .startsWith(searchKey.toLowerCase());

            }

        });

        System.out.println("Got " + searchKey + " results");

    }



    @DataProvider

    private Object[][] searchStrings() {

        return new Object[][] { { "TestNG" }, { "Selenium" } };

   }



    @AfterSuite

   public void quitDriver() throws Exception {
        driver.quit();

    }

OUTPUT::
Driver used is: FirefoxDriver: firefox on WINDOWS (ab3f6869-6669-4ccf-8e8f-9479f35aa790)

Search TestNG in google

Enter TestNG

submit

Got TestNG results

Search Selenium in google

Enter Selenium

submit

Got Selenium results



===============================================

TestNgSeleniumSuite

Total tests run: 2, Failures: 0, Skips: 0

===============================================