Search This Blog

Friday, 23 October 2015

Capture full screen screenshot using Selenium + Java

It is always a good idea to have a screenshot for investigating what was the state of the application at the time of exception/halt of execution.

Although Selenium WebDriver provides default functions to take the screenshots of the browser at the exception. See example here

The alternate is to capture the full screenshot (Screenshot covering the full desktop) at the time of exception or error occurred on the screen.

Note: When the test execution is failing because of "Model Pop Up" on the browser, default function of the WebDriver will not be able to capture the Model Pop Up in the screenshot.

Git Hub Link



import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

public class FullScreenShot {
    final static String fileLocation = "D:\\ScreenShot\\";


    public static void main(String[] args) {
        try {
            WebDriver driver = new FirefoxDriver();
            driver.get("http://www.testautomation4all.com");
            driver.findElement(By.id("some-non-existing-element")).click();
        } catch (Exception e) {
            captureEnirePageScreenshot("Unexpected error");
        }

    }

    public static void captureEnirePageScreenshot(String screenShotName) {
        try {
            // Capture the dimensions of the screen
            Dimension d = Toolkit.getDefaultToolkit().getScreenSize();

            // Convert the dimensions into rectangle object type
            Rectangle rec = new Rectangle(d);

            // Take the screenshot using the Robot instance
            Robot robot = new Robot();

            BufferedImage myImage = robot.createScreenCapture(rec);

            File img = new File(fileLocation + screenShotName + ".png");

            ImageIO.write(myImage, "png", img);

            System.out.println("Done");

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

How to Print Google Search result in the Eclipse Console?

Example to extract the text from google search result

To extract the search result count (which is displayed on the top) from the google search result, we have to

  1.  Find the WebElement of the search result and extract the WebElement
  2. The resulted string (result) is having extra characters like "About 5050 results"
  3. Extract the sub string from the obtained result string
  4. Replace all the extra characters from the result string
  5. Now parse the String to number format to convert the string to number.
GitHub Url

The program for the above example is as below



import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;

public class GoogleSearchResult {
    public static void main(String[] args) throws InterruptedException {
        Selenium selenium = new DefaultSelenium("localhost", 4444, "firefox", "http://www.google.com/");
        selenium.start();
        selenium.open("/?gws_rd=ssl");
        selenium.type("//input[@id='lst-ib']", "test automation 4 all");
        selenium.click("name=btnG");
//        selenium.waitForPageToLoad("30000");
        Thread.sleep(2000);
        String result = selenium.getText("id=resultStats");
        System.out.println("The Raw format" + result);

        result = result.substring(7, result.indexOf("result"));
        System.out.println("After extracting the substring of the result : " + result);

        result = result.replaceAll(",", "").trim();
        System.out.println("Removing the extra characters from the remaining string " + result);

        System.out.println("Now the remaining string is in the String format. Converting them to the Integer format");
        int searchResultCount = Integer.parseInt(result);

        System.out.println("Total Number of search results : " + searchResultCount);

        selenium.stop();
    }

}

Thursday, 22 October 2015

Page Object Model - Example


An example to create a small validation test using Page Object Model

All we will need for this are
  1. One class file for every Page (Page Objects will be defined in this class)
  2. One class file for invoking/writing the tests
Lets start creating the Page Object file
(To make life simpler, I've opted to write a test the google Home page and the Search Result Pages)

This is the Home Page related Class File

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class HomePageTest {
    final String xpathToLogo = "";
    final String xpathToSearchBox = "";
    final String xpathToSearchButton = "";
    final String xpathToImFeelingLuckyButton = "";
    final String xpathToAboutLink = "";
    final String xpathToGmailLink = "";
    final String xpathToImagesLink = "";
    final String xpathToSearchResult = "";

    WebDriver driver = new FirefoxDriver();

    @Before
    public void setUpBrowser() {
        driver.get("http://www.google.com");
    }

    @Test
    public void validateHomePageElements() {
        Assert.assertTrue("Logo is not displayed", driver.findElement(By.xpath(xpathToLogo)).isDisplayed());
        Assert.assertTrue("Search text box is not displayed", driver.findElement(By.xpath(xpathToSearchBox)).isDisplayed());
        Assert.assertTrue("Search Button is not displayed", driver.findElement(By.xpath(xpathToSearchButton)).isDisplayed());
        Assert.assertTrue("Im Feeling lucky link is not displayed", driver.findElement(By.xpath(xpathToImFeelingLuckyButton)).isDisplayed());
        Assert.assertTrue("About Link is not displayed", driver.findElement(By.xpath(xpathToAboutLink)).isDisplayed());
        Assert.assertTrue("Gmail Link is not displayed", driver.findElement(By.xpath(xpathToGmailLink)).isDisplayed());
        Assert.assertTrue("Image Link is not displayed", driver.findElement(By.xpath(xpathToImagesLink)).isDisplayed());
    }

    @Test
    public void validateSearchResultPageElements() {
        Assert.assertFalse("Image Link is displayed", driver.findElement(By.xpath(xpathToImagesLink)).isDisplayed());
        Assert.assertFalse("Gmail Link is displayed", driver.findElement(By.xpath(xpathToGmailLink)).isDisplayed());
        Assert.assertTrue("Search Results are not displayed", driver.findElement(By.xpath(xpathToSearchResult)).isDisplayed());
    }
}

This is the Search Result Page Class file

public class SearchResultPage {
     public SearchResultPage() {
        isLogoDisplayed();
        isPagenationDisplayed();
        isTitleCorrect();
        isSearchButtonDisplayed();
    }

    private void isLogoDisplayed() {
        System.out.println("Logo displayed..??");
    }

    private void isSearchButtonDisplayed() {
        System.out.println("Search Button displayed..??");
    }

    private void isPagenationDisplayed() {
        System.out.println("Pagination displayed..??");
    }

    private void isTitleCorrect() {
        System.out.println("Title Correct..??");
    }

    public  void isSearchResultDisplayed() {
        System.out.println("This is where I can test some other test");
    }

}

This is from where we invoke the tests.

import org.junit.Test;

public class SearchResultPageTest {
    @Test
    public  void validateSearchResultPage() {
        // By creating the object of the SearchResultPage() class, the validations are done
        new SearchResultPage();
    }

    @Test
    public void validateSomethingSpecial() {
        SearchResultPage searchResultPage = new SearchResultPage();
        searchResultPage.isSearchResultDisplayed();
    }
}



Wednesday, 21 October 2015

Page Object Model

Hello All,

In this blog post, let us discuss about the Page Object Model structure in Automation Testing.
Page Object Model (POM) is a very powerful way of testing the web applications.

In this POM, testing the web pages is very simple and it is an organized way. This helps to minimize the number of function calls and optimizes tests.

To illustrate the difference, lets take two examples.

Example to validate the webpage normally

If we are not using Page Object Model, we have to validate the elements separately.

See picture below


Example with POM way of validating pages

Using POM, we need not explicitly validate the page elements separately.
See Picture below




Learn more on how to create a POM with examples here

Tuesday, 13 October 2015

BDD configuration with Selenium Automation

Cucumber – JVM
1.       Introduction to BDD
2.       Introduction to Cucumber
a.       Life without Cucumber
b.      Need of Cucumber
c.       Advantages of Cucumber
3.       Understanding Maven Project
a.       Installation
b.      Setting environment variables
c.       POM
d.      Project Structure
4.       Examples using Maven
a.       Configuring dependencies
b.      Configuring Profiles
5.       Examples with Selenium
6.       Configuring the Cucumber Jars using Maven
7.       Understanding the Cucumber Approach
8.       Different Keywords used in Cucumber
a.       Feature
b.      Scenario
c.       Scenario Outline
d.      Examples
e.      GIVEN
f.        WHEN
g.       THEN
h.      AND
i.         BUT
9.       Regular Expressions in Java
10.   Learning to write Regex
11.   Passing values to Step-definitions in different formats
a.       String
b.      Boolean
c.       Numbers
d.      List
e.      Maps
f.        @Format…
12.   Results/Reports

Wednesday, 7 October 2015

Configure Cucumber (BDD) in Java

Cucumber Configuration Steps:

Configuring Cucumber BDD tool in Java can be achieved by following the below simple steps: 

Step 1: Install the following softwares
             Java (JDK And JRE) 
             Java IDE - To write the code 
                Maven - Centralized repository for all the jar files


Step 2: Create a simple Maven Project in the Java IDE                    
                The Maven project structure looks like this:
                                <<ProjectName>>
                                |-- pom.xml
                                `-- src
                                       |-- main
                                       |   |-- java
                                       |   `-- resources
                                       `-- test
                                              |-- java
                                              `-- resources



Step 3: (Optional step in most of the IDE. Mandatory in ItelliJIdea Ide)   
                Src -> main -> java - as Source root
                Src -> test -> java - as Test source root
                Src -> test -> resources - as "Resources for Test Source"

Add the following maven dependencies to the POM:
                <dependency>
                                <groupId>info.cukes</groupId>
                                <artifactId>cucumber-java</artifactId>
                                <version>1.2.2</version>
                </dependency>
                <dependency>
                                <groupId>info.cukes</groupId>
                                <artifactId>cucumber-core</artifactId>
                                <version>1.2.2</version>
                </dependency>
                <dependency>
                                <groupId>info.cukes</groupId>
                                <artifactId>cucumber-junit</artifactId>
                                <version>1.2.2</version>
                </dependency>
                <dependency>
                                <groupId>info.cukes</groupId>
                                <artifactId>cucumber-picocontainer</artifactId>
                                <version>1.2.2</version>
                </dependency>

Alternatively: If working on a non-maven project, download the respective jar files and add them to the project build path

Action: Save the POM.xml and clean install
Observation:  This should automatically download the required jar files into the Maven repository.
                                               
Step 4: Create files to resemble the folder structure of the project like below:
projectName
|-- pom.xml
`-- src
    |-- main
    |   `-- java
    |         `-- packageName
    |               `-- Sample.java
    `-- test
        |-- java
        |     `-- packageName
        |                      |-- RunCukesTest.java
        |           `-- Definitions.java
        `-- resources
              `-- packageName
                    `-- demo.feature


Details of the files:
1. Demo.feature is the Cucumber feature file.
                File Description: This contains the cucumber steps in Given When Then format
2. Defintions.java is the bridge between the actual java code and the GWT (Given When Then) format files.
   File Description: This contains the references to the functions which are to be invoked for every step. In general, this type of file(s) can be called as <<featureName>>StepDefs.java
3. RunCukesTest.java is the configuration file which holds details of the "Features Files"
4. Sample.java contains the actual java code. This code can be referenced from definitions.java

The source code of these files will be discussed in detailed

Step 5:
 (Assuming that the code is placed in the respective files)
1.       Open RunCukesTest.java
2.       Run the file as Junit Test
                               
                Observation:
This should trigger the execution.
                        As a result, the test steps defined in "demo.feature" are invoked.
                        Compiler finds the respective step definitions from "Definitions.java"
                        Defintions.java calls the functions/executes the logic to complete the test



Tuesday, 6 October 2015

BDD - Behaviour Driven Development


Need for BDD:

To understand the need of BDD, let us throw some light on “What in case of Absence of BDD”.
1. Requirement Analyst writes Acceptance Tests to determine if the product is doing right Thing
2. Developer writes Unit Tests to determine if the code is doing things RIGHT
3. Automation test script (using any tool) to cater regression/functional testing
               
Now, we have three different documentation/levels of definitions i.e. with Business, Developer and QA teams respectively for the same Application under development.

- There are high chances that, the gap between "Business requirement", "Development Specification" and "Acceptance Scenarios"
                - This is a big disadvantage, which ends up in more time to deliver a quality product.

BDD unites all the three definitions into ONE, which eventually minimizes the gap between Requirements, Developer & QA.

Advantages of BDD:
ü  Well defined documentation technique, which conveys the requirement to all the stake holders involved in the complete Software Development Life Cycle in a very simple language.
ü  The steps written in BDD could be understood by Business, Requirement Team,  Acceptance Team, Quality Assurance (Manual and Automation) and also to the developers.

BDD Format
                BDD follows a very simple format using simple keywords.
                Keywords like "Given", "When", "Then", "AND".
                                Given - used to define a precondition
                                When - used to define Actual test step
                                Then - used to define Observation (Expected behaviour)
                                And - used to connect two steps (Anywhere)
These keywords can be used to convey the requirement in a very simplified manner to avoid confusions. 


See an example here


The cucumber format can clearly convey the requirement to the entire stake holders, as they are very understandable.
Cucumber format removes the gap between the "Functional Specifiction", "Business Requirement Document", "Acceptance Specifications", etc