Tuesday 8 September 2015

Java Essentials for a good Selenium Automation Tester


To become good selenium automation tester, you must be proficient with some concepts of java.
If you’re then you can write excellent code with selenium and java.

Below I have listed those java concepts which selenium tester must be proficient.

OOP’s concept - Class, Objects Polymorphism, Inheritance and Encapsulation.

Java Programming essentials - Object Instances, method overloading/overriding concepts and packages.

Looping statements – This will help us in scenarios like, iterating through a large table to find a record that you want and Running the same test for multiple numbers of times.

Control Statements – While, do-While, Switch, if statements – This will help us in writing the scripts for a multiple scenario statements and decision making scenarios.

Arrays Concepts – This will help us in having some set of data of same type in a static way.

Java Collections Framework – ArrayLists.

File Streams – This will be helpful in externalization of data through CSV, Excel or Java Properties file.


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();
}