Wednesday, January 13, 2016

Page Object Model (POM) & Page Factory in Selenium

Page Object Model | POM

Creating Selenium test cases can result in an unmaintainable project. One of the reasons is that too many duplicated code is used. Duplicated code could be caused by duplicated functionality and this will result in duplicated usage of locators. The disadvantage of duplicated code is that the project is less maintainable. If some locator will change, you have to walk through the whole test code to adjust locators where necessary. By using the page object model we can make non-brittle test code and reduce or eliminate duplicate test code. Beside of that it improves the readability and allows us to create interactive documentation. Last but not least, we can create tests with less keystroke. An implementation of the page object model can be achieved by separating the abstraction of the test object and the test scripts.

·          Count and print no. of links present on webpage using Page Object Model

1.    In order to initialize the elements which are declare using @FindBy. We use initElements method of Page Factory Class

import java.util.List;

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

public class Flipkartpage
{
   @FindBy(xpath="//a")
   private List<WebElement> allLinks;
  
   public Flipkartpage (WebDriver driver)
   {
          PageFactory.initElements(driver,this);
   }
   public void PrintNoofLinks()
   {
          //To count no. of links present on webpage
          System.out.println(allLinks.size());
          for (WebElement pagelink : allLinks)
          {     
                 String linktext = pagelink.getText();
                 String link = pagelink.getAttribute("href");
                 System.out.println(linktext+" ->");
                 System.out.println(link);
          }
   }
}

2.   Now create the class of Main method

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

public class POM
{
   public static void main(String[] args)
   {
          WebDriver driver=new FirefoxDriver();
          driver.get("Page Url");
          Flipkartpage f=new Flipkartpage(driver);
          f.PrintNoofLinks();
          driver.close();     
   }
}


Sunday, January 10, 2016

Test Automation

Test Automation 
 
Before understanding what is meant by 'Test Automation' or 'Automation Testing', we've to first understand the answers for the following listed questions?

1.What is Manual Testing ?

Manual Testing is the process of validating and verifying whether the software program works as expected without using any automation tool (i.e. A Tester have to manually test each and every functionality of the software program without using any automation tool)

Validation is the process of checking whether the software given for test is according to the Client needs. i.e. to check whether the software meets the needs of the customer.
Verification is the process of checking whether the software given for testing correctly implements the specified functionality.

2. What is Regression Testing ?

Regression testing is the repetition of the earlier successful tests in order to make sure that changes to the software has not introduced side effects.

3. What is Automation Testing ?

It is the process of validating and verifying whether the software program works as expected using any  automation tool. (Automation tool performs the testing instead of a tester).

4. How can an Automation Tool perform testing without a tester ?

Creating Automation Scripts - Tester develops automation scripts using any language supported by the automation tool. ( For example Using Selenium Automation Tool the tester develops automation scripts using Java language)
Running the Automation Scripts -  Tester runs the above created automation scripts using Automation Tool's Run commands. ( For example Using Selenium Automation Tool's run commands the tester runs the above created Java automation scripts)
Viewing the Test Results generated by the Automation Tool - For each and every Run of the automation scripts, the Automation tool will generate results in a detailed report. Result report will show us whether the tests performed are functioning correctly or not.

5. What is the main purpose for Automating the Testing Process ?

Automation Testing main purpose is to automate the Regression tests. Automation testing is mostly helpful in large scale projects. That is when a small change is made to the source code of the software, the tester has to manually test each and every functionality of the large scale software, which takes lot of time for the testers to test the complete functionality from scratch. If instead the tester automates the complete software using any automation tool, he can just run the automation tests using the automation tool every time when a change is made to the source code of the project or when a new build is given for testing frequently. Ultimately it saves the testing time of testers and relives the testers from the stress.

6. What are the other advantages of Automation Testing ?

Less burden for testers - The amount of  time needed for testing repeated test scenarios on every new build is reduced to zero. As a result the burden for testers reduces.
Less Cost for the Business Clients - The Business Clients have to pay the testers for the number of hours they work. As the automation saves time, the client gets cost benefits.
Increase Test Coverage - As testing time gets reduced, the tester can cover testing other test scenarios within the provided time for testing.
Improves Testing Accuracy - In Manually Testing process, a tester may forget or wrongly test any test scenario. But while running automated test scripts, the computer wont forget or wrongly test the test scenarios.

7. What kind of applications are suitable for Automation Testing ?

If we know in advance that much of the functionality in our application will  be stable over time without needing any changes. We can definitely perform automation testing for this kind of Applications. But if any applications functionality keeps on changing, it means that the application is not stable, and this kind of applications wont be suitable for Automation.

8. Which tests can be automated ?

We're not going to automate the complete functionality of the Application. If the application is stable enough to automate, then as a tester we have to make a decision on filtering the test scenarios to find out the test scenarios that can be automated. We've to filter out the following types of test scenarios for automation:

Stable Tests - The tests that are not going to change in the upcoming builds
Smoke Tests - The tests that give a quick high level assessment on the quality of the build
Data Driven Tests - The tests which test the same functionality with different inputs and large data sets
Highest Priority Tests - The tests that you want to test often because of their priority over the other tests.

9. Is Automation Testing advantageous for Short Term Projects and the applications having very tight deadlines ?

In short term projects, there wont be enough time to build test automation. So manual testing will be more effective for Short Term. If an application is having a very tight deadlines, and its imperative that the testing get done with in that time frame, then manual testing is the best solution.

10. What is the goal of the Automation Testing ?


The goal of the automation testing is to reduce the number of tests to be run manually and not eliminate manual testing all together. Most of the testers who are new to Automation Testing thinks that - In order to automate their application they have to automate all the test cases of the Application. Assuming that all the test cases of the application to be automated is a wrong decision. We have to think of Automating the selected test cases of the application such that they reduce our burden and make our testing process more effective.

11. What are the most popular automation tools available in the market ?

Out of all the open source and commercial tools available in the market, the following are the two most popular tools:
  1. QTP  ( Commercial Tool - Supports Desktop and Web Applications )
  2. Selenium ( Open Source Tool - Supports only Web Applications )

Data Driven FrameWork

What is Data Driven Framework 
 
Selenium Webdriver Data-Driven Framework is where test input and output values are from data files (ODBC sources, CVS files, Excel files, and DAO objects) and are loaded into variables in captured or manually coded scripts.
In this framework, variables are used for both the input values and output verification values. The framework should include navigation through the program, reading of the data files, and logging of test status and information. All the processes should be in the test scripts. The framework should have the following features:
  • Well defined architectural design
  • Less time to test large data
  • Script execution in multiple environments
  • Easier, faster, and efficient analysis of result logs
  • Communication of results
  • Easy debugging and scrip tmaintenance
  • Robust and stable due to error and exception handling
  • 100% reliability of utility scripts, online execution and report packages.

Framework Architecture Design

Automation architecture package should include:

  • Config - Keeps all the configuration files such as property files
  • InputTestData - has files containing input data for application
  • OutputData - Contains downloaded documentations, images, fetched data in excel
  • TestReports - Contains ANT generated reports
  • Util package - Should contain all generic functions & business functions such as email configuration settings and all other utilities
  • TestLogs-Contain log file corresponding to tests
  • DAO - Classes for accessing persistent storage, such as to a database
  • Pages - Page classes for particular pages
The picture below displays general directory structure of the Framework.


 

How to connect Excel Sheet Using Selenium Web driver.

To get data from excel sheet or write data in excel sheet we require some other  api which available  on below link:
Steps :
1. Download apache poi form https://poi.apache.org/download.html link.
2. Unzip and import jar your project.
3.Use given API to connect to excel sheet
 
 
  • For Reading and write the data from excel sheet  
 public class BasicReadData {

    public static void main(String[] args) throws EncryptedDocumentException, InvalidFormatException, IOException
    {
        File src=new File("Path of excel sheet");
        FileInputStream fis=new FileInputStream(src);
        Workbook wb= WorkbookFactory.create(fis);
        Sheet s=wb.getSheet("Sheet1");
        int  rowdata=s.getLastRowNum();
        //Row r=s.getRow(0);
        //Cell c=r.getCell(0);
        //System.out.println(c);\
        for(int i=0;i<=rowdata;i++)
        {
            String string0=s.getRow(i).getCell(0).getStringCellValue();
            System.out.println(string0);
        }
        s.getRow(0).createCell(2).setCellValue("nishnt");
        FileOutputStream fout=new FileOutputStream(src);
        wb.write(fout);
        

    }

}
  • Count Cell in each row
    public class CountCellinEachRow {

        public static void main(String[] args)
        {
            try{
                FileInputStream fis=new FileInputStream("Path of excel sheet");
                Workbook wb=WorkbookFactory.create(fis);
                Sheet s=wb.getSheet("Sheet1");
                int i=s.getLastRowNum();
                System.out.println(i);
               
            }
            catch(Exception e){
               
            }
         }
             }
  •  Print No. of Cell Present in Excel Sheet
    public class PrintNoOfCell {

        public static void main(String[] args)
        {
            try{
                FileInputStream fis=new FileInputStream("Path of excel sheet");
                Workbook wb=WorkbookFactory.create(fis);
                Sheet s=wb.getSheet("Sheet1");
                for(int i=0;i<=s.getLastRowNum();i++)
                {
                    int n=s.getRow(i).getLastCellNum();
                    System.out.println(n);
                }
               
            }
            catch(Exception e){
               
            }
           
        }

    }
 

Drop Down or Select List in Selenium Web Driver.



Select Class Example....How to handle Select List or Drop Down

package basic;

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.openqa.selenium.support.ui.Select;

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

WebDriver driver=new FirefoxDriver();//launch browser
driver.get("http://piyush-pc/login.do");//navigate to actiTime login page
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.xpath("//input[@type='submit']")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 driver.findElement(By.linkText("Projects & Customers")).click();
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 WebElement selectlst=driver.findElement(By.name("selectedCustomer"));
 Select sel=new Select(selectlst);
    sel.selectByIndex(1);
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.findElement(By.xpath("//input[contains(@value,'Show')]")).click();
    Thread.sleep(3000);
    System.out.println("done");
}
}

Or
package app1;

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;

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

WebDriver driver=new FirefoxDriver();
System.out.println("done");
driver.get("http://piyush-pc/login.do");
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.xpath("//input[@type='submit']")).click();
Thread.sleep(2000);
driver.findElement(By.linkText("Reports")).click();
Thread.sleep(2000);
WebElement wb=driver.findElement(By.name("users"));
Select sel=new Select(wb);
System.out.println(sel.isMultiple());
sel.selectByIndex(0);
//sel.selectByIndex(1);

}


}

Dynamic Web List:
package app1;

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;

public class DynamicWebList {
public static void main(String[] args) {

WebDriver driver=new FirefoxDriver();
System.out.println("done");
driver.get("http://piyush-pc/login.do");
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.xpath("//input[@type='submit']")).click();
WebElement wb=driver.findElement(By.name("customerProject.shownCustomer"));
Select sel=new Select(wb);

List<WebElement> lst = sel.getOptions();

//display size of list
System.out.println(lst.size());
String expval="C";
boolean flag=false;
//display dynamic weblist item name
for (int i = 0; i < lst.size(); i++) {
System.out.println(lst.get(i).getText());
String val=lst.get(i).getText();
if(expval.equals(val))
{
sel.selectByVisibleText(expval);
flag=true;
break;
}
}
if(flag)
{
System.out.println("pass");
}
else {
System.out.println("fails");
}
}


}


Key Board Operation Example :
package basic;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;


public class KeyboardOperationExample {
public static void main(String[] args) throws InterruptedException {
WebDriver driver=new FirefoxDriver();//launch browser
driver.get("http://piyush-pc/login.do");//navigate to actiTime login page
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
String un= driver.findElement(By.name("username")).getAttribute("value");
   System.out.println(un);
//driver.findElement(By.name("pwd")).sendKeys("manager");
Thread.sleep(3000);
Actions act=new Actions(driver);
WebElement wb=driver.findElement(By.xpath("//input[@type='submit']"));
act.moveToElement(wb).perform();


act.sendKeys(Keys.SHIFT,Keys.DELETE).perform();
act.sendKeys(Keys.ENTER).perform();

}


}

Get All Web Elements Example...

package basic;

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 GetAllWebElementExamole {
public static void main(String[] args) {

WebDriver driver=new FirefoxDriver();//launch browser
driver.get("http://piyush-pc/login.do");//navigate to actiTime login page
driver.findElement(By.name("username")).sendKeys("admin");
String un= driver.findElement(By.name("username")).getAttribute("value");
   System.out.println(un);
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.xpath("//input[@type='submit']")).submit() ;
//to get all link element present in ui
List<WebElement> lst =driver.findElements(By.xpath("//a"));
//to get all web elements
//List<WebElement> lst1 =driver.findElements(By.xpath("//*"));
// System.out.println(lst1.size());
System.out.println(lst.size());

//show all
for (int i = 0; i < lst.size(); i++) {
System.out.println(lst.get(i).getText());


}
for (int i = 0; i < lst1.size(); i++) {
System.out.println(lst1.get(i).getText());

}

}

}


Auto Suggestion.....
package pac1;

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

public class AutoSugesstEditBox {

public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.co.in/?gws_rd=cr");
driver.findElement(By.id("gbqfq")).sendKeys("cognizant wiki" ,Keys.ENTER);


}


}