Tuesday, 8 September 2015

Page Object Model (POM)



This is widely used concept in the world on selenium webdriver also known as POM.
With the use of POM, we can increase readability of code also it is easy to maintain and user can reuse it.

        Basically POM is design pattern to create object repository (OR).
        In POM, we are maintaining different pages for different web pages. This page class
        contains      
        Elements along with page methods which perform operation on web element.

The main advantage of Page Object Model is that if the UI changes for any page, it don’t require us to change any tests, we just need to change only the code within the page objects.

Below I have given example of POM

      //Class for page objects (elements) 

 public PageName(WebDriver driver)  
 {        
     this.driver = driver;  
    
    //This initElements method will create all WebElements  
    //PageFactory.initElements(driver, this);  
     PageFactory.initElements(new AjaxElementLocatorFactory(driver,     
     Constants.WebDriverWaitDuration), this);  
 }  
        
        
 /*  
  * All WebElements are identified by @FindBy annotation  
  * @FindBy can accept tagName, partialLinkText, name, linkText, id, css, className, xpath as      
  * attributes.  
  */        
   
   
   
   
 Say we have text box  
        
 @FindBy(Locator="LocatorValue")  
 public WebElement NameForElement;  
        
 //Method to enter input  
 public void EnterInput(String text)  
 {  
      NameForElement.clear();  
      NameForElement.sendKeys(text);  
 }  
   
 //If Element is button  
 public void ClickOnButton()  
 {  
      NameForElement.click();  
 }  
   
 //If Element is drop-down  
 public void SelectValueFromDropDown(String visibletext)  
 {  
      new Select(NameForElement).selectByVisibleText(visibletext);  
 }  
   

Lets consider two different cases of writing code as below, in case 1  there no use of POM concept and in case 2 I have used POM

       Case 1 
 Without POM 

 driver.findElement(By.id("username")).sendKeys("testuser");  
 driver.findElement(By.id("password")).sendKeys("testuser");  
 driver.findElement(By.id("signIn")).click();      
   
   

Case 2 
With POM 
Say we are working with login and elements resides in loginpage 
Code will look like below –  

 loginpage. EnterUserName(“testuser”);  
 loginpage. EnterPassword(“testuser”);  
 loginpage. ClickOnLoginButton();  
   

So suppose I have used login code in 10 classes as per case 1, and if there is change in locator value. In that case I have to make changes in all 10 classes but if code is written as per case 2, I have to make changes at one place only where all elements are resides.


Below I have tried to list out some benefits of POM

  1. Code is more readable and robust.
  2. Avoid duplication of code.
  3. Improves the maintainability of tests (Useful in Agile methodology based projects).
  4. Simple and clear tests.
  5. Good support of tests, because everything is stored in one place.
  6. The UI changes, the fix need only be applied in one place.
  7. Code re-use: Able to use the same page object in a variety of tests cases.

 

Mouse Hover functionality with selenium



Handling Mouse hover is one of the complex events for Selenium Users

We can not handle Mouse Hover directly by any command; we have to use some javascript to help us in mouse hover.

In this post I have created a method which will help selenium users to handle mouse hover event.

You can easily call that method into your script logic.

 public void MouseHover(String locatorvalue ) throws InterruptedException  
 {  
      Actions action = new Actions(driver);  
      WebElement element = driver.findElement(By.id(locatorvalue));  
      action.moveToElement(element).build().perform();  
      Thread.sleep(5000);  
             
             
      String javaScript = "var evObj = document.createEvent('MouseEvents');" +  
      "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false,        
  false, false, 0, null);" +  
      "arguments[0].dispatchEvent(evObj);";  
   
      WebElement element1 = driver.findElement(By.id(locatorvalue));  
      ((JavascriptExecutor)driver).executeScript(javaScript, element1);  
             
      Thread.sleep(5000);  
 }  
   

You can call this method as  
 MouseHover(locator value );  

File download with Selenium WebDriver



Most of the selenium user is facing problem while handling file download scenario.
In file downloading we have to deal with windows pop-up also we need to verify whether file is downloaded or not.

To deal with this scenario with have to work with firefox profile.
Below you can check the code, here you can verify file by its name or if name is randomly generated then you can verify file by its extension.

 @BeforeClass  
 public void Setup() throws Exception  
 {  
 driver = new FirefoxDriver(ffprofile());       
 File directory = new File(FIleDownloadPath);  
 delete(directory); //create a function delete with code to delete directory and its files  
 }  
   


//Method where user will download a file and then verify

 @Test  
 public void DownloadAndVerify()   
 {  
      driver.get(URL);  
        
 //Go to the place where link / button is placed for download  
 // Click on it to download file  
   
 Assert.assertTrue(VerifyFileDownloadWithName (FIleDownloadPath, "Name of file with extension"), "Failed to download Expected document");  
   
 //if file name is random then you can verify by extension  
 Assert.assertTrue(VerifyFileDownloadWithExtension (FIleDownloadPath, ".extension of file"), "Failed to download document which has extension ".extension of file ");  
 }  
   

  



//To set download functionality, with this download pop-up will not appeared
 
 public static FirefoxProfile ffprofile() throws Exception  
 {  
       FirefoxProfile firefoxProfile = new FirefoxProfile();  
       firefoxProfile.setPreference("browser.download.folderList",2);  
       firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);  
       firefoxProfile.setPreference("browser.download.dir",downloadPath);  
      firefoxProfile.setPreference "browser.helperApps.neverAsk.saveToDisk",  
      "text/csv,application/x-msexcel,application/excel,application/x-excel," +  
      "application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/" +  
                     "msword,application/xml"  
             
       return firefoxProfile;  
 }  
   





//Verify file downloaded by its Name
 
 public boolean VerifyFileDownloadWithName (String FIleDownloadPath, String fileName)   
 {  
      boolean flag = false;  
      File dir = new File(FIleDownloadPath);  
      File[] dir_contents = dir.listFiles();  
           
      for (int i = 0; i < dir_contents.length; i++)   
      {  
           if (dir_contents[i].getName().equals(fileName))  
                 return flag=true;  
       }       
   
      return flag;  
 }  
   




//Verify file downloaded by its Extension
 
 private boolean VerifyFileDownloadWithExtension(String FIleDownloadPath, String ext)  
 {  
  boolean flag=false;  
  File dir = new File(FIleDownloadPath);  
  File[] files = dir.listFiles();  
  if (files == null || files.length == 0)   
  {  
      flag = false;  
  }  
  for (int i = 1; i < files.length; i++)   
  {     
       if(files[i].getName().contains(ext))   
          {   
             flag=true;   
           }  
   }   return flag;   
 }  
   





With this code, hope you are set to handle Download Functionality.



Thursday, 3 September 2015

File upload – Selenium WebDriver



There are different ways to upload file, below you can see code for same.

File upload using sendKeys

If   input type="file"  is used the you can upload file using  sendKeys
Suppose “FileUpload.txt” is file you want to upload, and say file is under your project only

 File file = new File("FileUpload.txt ");  
 WebElement upload = driver.findElement(By.locator(LocatorValue));  
 upload.sendKeys(file.getAbsolutePath());  



File upload using Robot


You can upload file using robot framework as below

 File file = new File("FileUpload.txt");  
 WebElement upload = driver.findElement(By.locator(LocatorValue));  
 upload.click();  
 StringSelection filepath = new StringSelection(file.getAbsolutePath());  
 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(filepath, null);  
   
 //imitate mouse events like ENTER, CTRL+C, CTRL+V  
 Robot robot = new Robot();  
 robot.delay(1000);  
   
 robot.keyPress(KeyEvent.VK_CONTROL);  
 robot.keyPress(KeyEvent.VK_V);  
 robot.keyRelease(KeyEvent.VK_V);  
 robot.keyRelease(KeyEvent.VK_CONTROL);  
 robot.keyPress(KeyEvent.VK_ENTER);  
 robot.keyRelease(KeyEvent.VK_ENTER);  
 robot.delay(1000);  
   



You can also upload file using AutoIT tool


 

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.