Wednesday, 2 September 2015

Handling multiple windows with Selenium WebDriver



With the help of below code you can easily handle different windows and can perform different operations

 

 
       // Store current window handle  
      String winHandleBefore = driver.getWindowHandle();  
   
      //Click on element which opens new window  
   
      // Switch to new window opened  
      for (String winHandle : driver.getWindowHandles())  
      {  
        driver.switchTo().window(winHandle);  
      }    
   
     // perform operation that opens new window  
           
     // Close the new window  
      driver.close();  
   
    // Switch back to original window  
    driver.switchTo().window(winHandleBefore);  
   

 

Selenium WebDriver and Javascripts alerts/ pop-ups

Generally JavaScript pop-ups are generated by web application and hence they can be easily controlled by the browser.         
Built into Selenium is the ability to switch to an alert window and either accept or dismiss it.
Below are the ways to accept / dismiss alert

// Here you can accept the alert and can get text of alert


    public String AcceptAlertAndGetText()  
       {  
              //Switch to alert  
              Alert alert = driver.switchTo().alert();  
               //Get text of the alert  
               String AlertText = alert.getText();  
               //Accept the alert  
               alert.accept();  
          return AlertText;  
      }  




 
//Here you can dismiss the alert and can get text of alert

 public String DismisAlertAndGetText()  
 {  
           //Switch to alert  
           Alert alert = driver.switchTo().alert();  
          //Get text of the alert  
           String AlertText = alert.getText();  
         //Dismiss the alert  
         alert.dismiss();  
      return AlertText;  
 }  


CSS Selectors for Selenium with example



This post is all about CSS selectors for selenium. CSS is faster and simpler than Xpath particularly in case of IE browser where Xpath works very slowly.


We can detect element in different ways as below


 

# Element by ID
Event is ID
css=#Event

# Element by Name
Query is name
css=input[name= Query]

# Element by Class
Example is class
css=.Example a

# Element by href
css=a[href=’URL’]

# Locating Child or subchild
Here a is child of div
css= div a

# Next sibling by + sign
Say Registration is ID and small is next sibling
#Registration + small

#Element name start with go
input[name^="go"]

#Element name end with go
input[name$="go"]

#Matching by inner text
Search is inner text
css=a:contains('Search')

 #Choosing specific element

  • Automation Tools
  • QTP
  • Selenium
If we want to select the second li element (Selenium) in this list, we can use the nth-of-type, which will find the fourth li in the list.

css=ul#recordlist li:nth-of-type(2)




Thursday, 10 October 2013

WebDriver TestNG Parameterization with DataProvider


For Parameterization in WebDriver, you can have different way..I have listed 2 ways with TestNG + DataProviderYou can take input from xls and store it in DataProvider and then you can pass that to your test.In other case, you can directly put the data in DataProvider, and can access them. You can find the details below...

1)Take Input From Excel

public class TS_Login
{
   WebDriver driver = new FirefoxDriver();

@Test(priority=1)
public void testing()
 {
   driver.get("URL of the website");
  }

@Test(dataProvider="login", priority=2)
public void TS1_LoginFunctionality(String Email,String Pass)throws Exception
 {
   driver.get("Sign In URL");
   driver.findElement(By.id("signin-link")).click();
   driver.findElement(By.id("signin-email")).sendKeys(Email);
   driver.findElement(By.id("signin-pw")).sendKeys(Pass);
   driver.findElement(By.id("signin-submit")).click();
}

@DataProvider
public Object[][] login() throws Exception
 {
   Object[][] testObjArray = getTableArray("Path Of Excel File","Sheet1","");
   return (testObjArray);
 }

//Get the data from excel and store in Array

public static Object[][] getTableArray(String xlFilePath, String sheetName, String tableName)    throws Exception
     {   
        String[][] tabArray = null;
        try
        {
            Workbook workbook = Workbook.getWorkbook(new File(xlFilePath));
            Sheet sheet = workbook.getSheet(sheetName);
            int ci,cj, totalRows = 0, totalCols =  0;
            totalRows = sheet.getRows();
            totalCols = sheet.getColumns();
            System.out.println("total cols = " + totalCols);
            System.out.println("total rows = " + totalRows);
            tabArray=new String[totalRows][totalCols];
            ci=0;
          for (int i=1;i (less than) totalRows;i++,ci++)
   {
cj=0;
for (int j=0;j(less than) totalCols;j++, cj++)
                {
                    tabArray[ci][cj]=sheet.getCell(j,i).getContents();
                    System.out.println(tabArray[ci][cj]);
                }
            }
         }
         catch (FileNotFoundException e)
         {
             System.out.println("Could not read the Excel sheet");
             e.printStackTrace();
         }
         catch (IOException e)
         {
             System.out.println("Could not read the Excel sheet");
             e.printStackTrace();
         }
         return(tabArray);
     }
}
Note : Please replace (less than) with  < 

2)Input with DataProvider

public class dataprovider {

WebDriver driver = new FirefoxDriver();

@Test(priority=1)
public void testing()
 {
   driver.get("URL of the website");
  }

@Test(dataProvider = "excelData", priority = 2)
public void executeTest(String name, String numbn) throws InterruptedException
 {
   driver.findElement(By.id("signin-link")).click();
   driver.findElement(By.id("signin-email")).sendKeys(name);
   driver.findElement(By.id("signin-pw")).sendKeys(numbn);
   driver.findElement(By.id("signin-submit")).click();
 }

@DataProvider(name = "excelData")
public Object[][] data(){
return new Object[][]{
                       {"Test","asd"},
                       {"More Testing","asd"},
                       {"Last Test","asd"}};
 }
}



Thursday, 18 July 2013

Start Selenium RC Server Within Code.


Now there is no need to start selenium server by going to command prompt and calling to server.

You can directly start the server in your script itself.
You just need to import
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;

The code will look like -

import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;

public class tet extends SeleneseTestCase {
private Selenium selenium;
public SeleniumServer seleniumserver;


@Before
public void setUp() throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
seleniumserver = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "https://www.google.co.in/");
seleniumserver.start();
selenium.start();
}

Tuesday, 11 June 2013

Android App : Automtion Testing Tools - Part II

Descriptions

Below we have listed different tools with their advantages and disadvantages.

Monkey

Monket tool is designed to simulate this situation. The Monkey tool, a part of the Android SDK, sends a stream of random user events. Command line parameters specify the number of user actions, the ratio of each event type, and a name of a package.
Advantages
  • Monkey tool is zero maintenance costs.
  • Stress testing can detect non-trivial bugs.
Disadvantages
  • Monkey can’t simulate complex workloads such as authentication. In such cases, application functionality remains untested.
  • Games with complex control that require quick reactions and complex gestures will be completed at the beginning, or do not begin.
  • It’s very difficult to reproduce errors found by Monkey.
  • Monkey doesn’t check application status during the test.

MonkeyRunner


You can not only develop Android device control scripts using MonkeyRunner, you can also write scripts to test the application on a specific device. Its like record and play back tool.
Advantage
  • Flexible
Disadvantages
  • The complexity of writing scripts, even in simple cases.
  • Developing monkeyrunner scripts takes a lot of time, so this method is usually not justified. However, in special cases, this method might work.

Robotium

Robotium is not a part of Android SDK, and it’s distributed under the Open Source license.
Robotium scripts define actions on the application UI level rather than the input device level.
For example, a script needs to tap on an «OK» button. The monkeyrunner script will be implemented as “Tap at the screen point (x0, y0)”. A Robotium script will be implemented as “Press the button with the text “OK” .”
When actions are described at the interface level, the testing script can be made independent of interface layout, screen resolution, and orientation.
Additionally, Robotium allows you to check the application response to the action.For example, after clicking the «OK» button, the list with the “Item 1” item should appear.You can check list element names with Robotium. If you check the application state after each step, it is easy to find at which step the error occurred.
Disadvantages:
  • You need to develop a test script in Java* for each application. This requires programming skills and time.
  • When the application interface changes, the event sequence must be redone.
In general, Robotium allows you to develop the highest quality test cases with adequate cost.


Feature Matrix



Monkey
MonkeyRunner
Robotium
License
Available with Android SDK
Available with Android SDK
Open source
Random user actions
Yes
No
No
Record and Playback
No
Yes
Placback
available
Script Complexity
-
Yes
Yes
Define actions on
-
Input device level
Application
UI level
Script language
-
Python
Java







Maintenance costs
No
Need to modify script if UI changes
Need to modify
script if UI
changes



Summary

Automated testing with Monkey is a good starting point for any application. It is possible that this method will show adequate results for a particular application.

Monday, 27 May 2013

Android App : Automtion Testing Tools - Part I

Introduction

As the mobile platform continues to pervade all aspects of human activities,
and mobile apps on such platform tend to be faulty just like other types of software,
There is a growing need for automated testing techniques for mobile applications.

 Why Do Automate - 
  • Reduce ongoing costs of regression testing across multiple devices.
  • Create Automation which is reusable across multiple handsets with minimal changes to scripts to cater existing as well as future handsets.
  • To minimize challenges in manual testing, load testing, crashes
Limitation of Manual Testing -
  • Diversity of devises
  • OS versions
  • Different h/w configuration
  • Different screen sizes

Different Automation Tools

  1. Monkey
  2. Monkey Runner
  3. Robotium
  4. Selenium Webdriver
Monkey -
  • The Monkey is a command-line tool that that you can run on any emulator instance or on a device.
  • We can send random user events which acts as a stress test on the application
  • Help to determine crashes or any sort of unhandled exception
  • When the Monkey runs, it generates events and sends them to the system
Monkey Runner -
  • Multiple device control
  • Functional testing: can run an automated start-to-finish test of an Android application. You provide input values with keystrokes or touch events, and view the results as screenshots.
  • It is like record and playback tool, will record user actions / input, we can execute those on emulator / devices
Robotium -
  • Open-source test framework
  • Need to write solid test case
  • The framework handles multiple Android activities automatically
  • Must have basic knowledge of Android programming.
  • Support testing on real devices
  • System and acceptance test
Android Webdriver -
  • Tests can only be written in Java
  • Android WebDriver models many user interactions such as finger taps, flicks, finger scrolls and long presses

Friday, 10 May 2013

Introduction To Quick Test Professional


Now along with selenium we will have post regarding different automation tools.
Quick Test Professional is one of the automation tool.


Quick Test Professional , popularly know by its acronym QTP is the functional automation testing tool from Mercury Interactive now acquired by HP. It is now called as HP Functional Test
QuickTest Professional is the solution for functional test and regression test automation.
QTP is easier to use and implement for both technical & non technical testers in comparison to other functional testing tools available.

QTP's Scripting Language is VB Script which is easy to use , understand and program.

Quick Test Professional is the most widely used tool for the purpose of Test automation and has emerged as the test automation tool of choice for the software industry.

Why QTP

  • It is easy even for a non-programmer to understand QTP and start adding test cases.
  • Support for record and playback and ability to edit scripts after recording. Also different recording modes are provided in QTP viz. Normal, Analog & Low level.
  • Excellent Object Identification process / mechanism
  • Ability to let you enhance the existing tests even without the AUT (Application under test) through active screen.
  • Supports all popular Automation frameworks - Keyword driven testing approach, Data driven testing approach, Modular testing approach, Hybrid frameworks etc.
  • QTP comes with an inbuilt IDE, which is simple and easy to use.
  • QTP can be integrated with Test management tools like QC (Quality Center), Test director and also functional test tools like Winrunner. The test cases can be mapped to the automation scripts and be executed from QC (Quality Center) itself. Also, it can kick off Winrunner test execution from within.
  • Easy to maintain different types of suites viz. Smoke, Sanity, Regression etc.
  • It comes with loads of inbuilt properties and methods in QTP as well as inbuilt functions in VBScripts
  • Use of Datatables/Excel files are easier and provides a variety of methods to play around with rows and columns.
  • Easy to maintain test iterations and data driving the tests through configurations.
  • Test reporting with all necessary details for analysis is provided.
  • Microsoft Object model can be implanted in QTP easily (Example – Word document object, Excel Object, Outlook Object, ADO objects, File system objects, DOM etc)


Monday, 31 December 2012

Happy New Year !!


Wish you and your family a Joyful, Bright, Healthy,Prosperous and Happiest New Year ahead!

Happy New Year 2013!!







Wednesday, 3 October 2012

Error Handling In Selenium RC

With help of error handling you can able to get details of failure.
If any of the steps in your tests fails then selenium will throw an exception and tests would stop. If you handle the exceptions using 'try catch', then you should be able to achieve what you are looking for. 

As an example, see the code below. This would handle the Element Not Found Error.And you can write that exception to file




public void test() throws Exception {
try {
selenium.open("http://seleniumhq.org/");
selenium.click("xpath=(//button[text()='Login'])[2]");
}catch (SeleniumException e){  //If any error occurs

try{
//Code to write error in file
FileWriter fstream = new FileWriter("e:/filename1.txt",true); //Will
                                           write error details here, if file doesn't exists it will create new    

BufferedWriter bw = new BufferedWriter(fstream);
bw.write("Test Project " + e.getMessage());
bw.newLine();
bw.close();
}catch(Exception a){  //For File handling Error
System.out.println("Error In File Handling");  
}
    }
}


Output
Test Project ERROR: Element xpath=(//button[text()='Login'])[2] not found