Monday, 24 February 2014

How To Close Popup Window in Selenium Webdriver


This Method will Solve Your Problem:


private void  handleWindow() {
 try {
      String parent = driver.getWindowHandle();

      Set<String> pops=driver.getWindowHandles();
       {
 Iterator<String> it =pops.iterator();
while (it.hasNext()) {

 String popupHandle=it.next().toString();
 if(!popupHandle.contains(parent))
{
                   driver.switchTo().window(popupHandle);
 System.out.println("Popu Up Title: "+ driver.switchTo().window(popupHandle).getTitle());
 driver.close();
  driver.switchTo().window(parent);  // control is moving to parent window
        }
       }
}
} catch (NoAlertPresentException e) {
         e.printStackTrace();
 }

}

Thursday, 20 February 2014

WebDriver’s most popular Commands


Selenium WebDriver is like a magic wand to automation tester to test the web application. Selenium WebDriver has not only  made automation more Object oriented through it OOPs API  but it has also solve the  the most complaining performance of browser launching in Selenium 1.0 and the most important thing that has given a panacea to automation engineers’ hand is its ability to Single Host origin policy.
Selenium WebDriver has left more impact on functional test coverage, like the file upload or download, pop-ups and dialog’s barrier
Today I am going to post most common functions used in Selenium WebDriver to make a journey of automation testing through WebDriver
  1. IsElementPresent/Text Present  function in Selenium WebDriver
    1. Finding elements by using function that take argument of By classprivate boolean isElementPresent(WebDriver driver, By by)
      try{
      driver.findElement(by);
      return true;
      }
      catch(Exception e)
      {
      return false;
      }
      }
    2. Using the size to decide whether element is there or not
      if(driver.findElements(Locator).size()>0
      {
      return true
      }else
      {
      return false
      }
      }
    3. Finding the text using the PageSourcedriver.PageSource.Contains("TEXT that you want to see on the page");
  2. Finding WebElement  by using various locators in WebDriver
    1. Using ID  WebElement welement = driver.findElement(By.id("Id from webpage"));
    2. Using Name  WebElement welement = driver.findElement(By.name("Name of WebElement"));
    3. Using Tag Name  WebElement welement = driver.findElement(By.tagName("tag name"));
    4. Using Xpath  WebElement welement = driver.findElement(By.xpath("xpath of  webElement"));
    5. Using CSS  WebElement welement = driver.findElement(By.CSS("CSS locator path"));
    6. Using LinkText  WebElement welement = driver.findElement(By.LinkText("LinkText"));
  3. Fetching pop-up message in Selenium-WebDriver
    this is the function that would help you in fetching the message

    public static String getPopupMessage(final WebDriver driver) {
    String message = null;
    try {
    Alert alert = driver.switchTo().alert();
    message = alert.getText();
    alert.accept();
    } catch (Exception e) {
    message = null;
    }
    System.out.println("message"+message);
    return message;
    }
  4. Canceling pop-up in Selenium-WebDriver
    public static String cancelPopupMessageBox(final WebDriver driver) {
    String message = null;
    try {
    Alert alert = driver.switchTo().alert();
    message = alert.getText();
    alert.dismiss();
    } catch (Exception e) {
    message = null;
    }
    return message;
    }
  5. Inserting string in Text Field in Selenium-WebDriverpublic static void insertText(WebDriver driver, By locator, String value) {
    WebElement field = driver.findElement(locator);
    field.clear();
    field.sendKeys(value);
    }
  6. Reading ToolTip text in in Selenium-WebDriver
    public static String tooltipText(WebDriver driver, By locator){
    String tooltip = driver.findElement(locator).getAttribute("title");
    return tooltip;
    }
  7. Selecting Radio Button in Selenium-WebDriver
    public static void selectRadioButton(WebDriver driver, By locator, String value){ List select = driver.findElements(locator);
    for (WebElement element : select)
    {
    if (element.getAttribute("value").equalsIgnoreCase(value)){
    element.click();
    }
    }
  8.  Selecting CheckBox in Selenium-WebDriver

    public static void selectCheckboxes(WebDriver driver, By locator,String value)
    {
    List abc = driver.findElements(locator);
    List list = new ArrayListArrays.asList(value.split(",")));
    for (String check : list){
    for (WebElement chk : abc){
    if(chk.getAttribute("value").equalsIgnoreCase(check)){
    chk.click();
    }}}}
  9. Selecting Dropdown in Selenium-WebDriverpublic static void selectDropdown(WebDriver driver, By locator, String value){
    new Select (driver.findElement(locator)).selectByVisibleText(value); }
  10. Selecting searched dropdown in Selenium-WebDriverpublic static void selectSearchDropdown(WebDriver driver, By locator, String value){
    driver.findElement(locator).click();
    driver.findElement(locator).sendKeys(value);
    driver.findElement(locator).sendKeys(Keys.TAB);
    }
  11. Uploading file using  Selenium-WebDriverpublic static void uploadFile(WebDriver driver, By locator, String path){
    driver.findElement(locator).sendKeys(path);
    }
  12. Downloading file in Selenium-WebDriverHere we will click on a link and will download the file with a predefined name at some specified location.
    public static void downloadFile(String href, String fileName) throws Exception{
    URL url = null;
    URLConnection con = null;
    int i;
    url = new URL(href);
    con = url.openConnection();
    // Here we are specifying the location where we really want to save the file.
    File file = new File(".//OutputData//" + fileName);
    BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
    BufferedOutputStream bos = new BufferedOutputStream(
    new FileOutputStream(file));
    while ((i = bis.read()) != -1) {
    bos.write(i);
    }
    bos.flush();
    bis.close();
    }
  13. Handling multiple Pop ups 
    read  Handling Multiple Windows in WebDriver
  14. Wait() in Selenium-WebDriver
    1. Implicit Wait :
      driver.manage.timeouts().implicitlyWait(10,TimeUnit.SECONDS);
    2. Explicit Wait:WebDriverWait wait = new WebDriverWait(driver,10);
      wait.until(ExpectedConditons.elementToBeClickable(By.id/xpath/name("locator"));
    3.  Using Sleep method of java
      Thread.sleep(time in milisecond)
  15. Navigation method of WebDriver Interface
    1. to() method (its a alternative of get() method)
      driver.navigate().to(Url);
      This will open the URL that you have inserted as argument
    2. back() – use to navigate one step back from current position in recent history syntax == driver.navigate().back();
    3. forward() – use to navigate one step forward in browser historydriver.navigate().forward();
    4. refresh() – This will refresh you current open urldriver.navigate().refresh();
  16. Deleting all Cookies before doing any kind of action  driver.manage().deleteAllCookies();
    This will delete all cookies
  17. Pressing any Keyboard key using Action builder class of WebDriverWebDriver has rewarded us with one class Action to handle all keyboard and Mouse action. While creating a action builder its constructor takes WebDriver as argument. Here I am taking example of pressing Control key
    Actions builder = new Actions(driver);
    builder.keyDown(Keys.CONTROL).click(someElement).click(someOtherElement).keyUp(Keys.CONTROL).build().perform();
    When we press multiple keys or action together then we need to bind all in a single command by using build() method and perform() method intend us to perform the action.
    In the same way you can handle other key actions.
  18. Drag and Drop action in Webdriver
    In this we need to specify both WebElement  like Source and target and for draganddrop Action class has a method with two argument so let see how it normally look like
    WebElement element = driver.findElement(By.name("source"));
    WebElement target = driver.findElement(By.name("target"));
    (new Actions(driver)).dragAndDrop(element, target).perform();

Wednesday, 19 February 2014

how to select a checkbox using webdriver


1.If all checkbox's having Inside one <td> like As
<td>
<input type="checkbox" name="module" value="xxx">
xxx
<br>
<input type="checkbox" name="module" value="yyy">
yyy
<br>
<input type="checkbox" name="module" value="zzz">
zzz
<br>

</td>


 webdriver selecting checkbox script is:

driver.findElement(By.xpath("//input[@name='module' and @value='zzz']")).click(); 
driver.findElement(By.xpath("//input[@name='module' and @value='yyy']")).click();
driver.findElement(By.xpath("//input[@name='module' and @value='xxx']")).click();



2.if all checkbox having one <td> with <table> structure like as

<td width="50%" align="left">
<table border="0" align="left">
<tbody>
<tr>
<td align="left">
<input type="checkbox" name="modules" value="3" style="width:10px">
</td>
<td align="left">zzz</td>
</tr>
<tr>
<td align="left">
<input type="checkbox" name="modules" value="2" style="width:10px">
</td>
<td align="left">yyy</td>
</tr>
<tr>
<td align="left">
<input type="checkbox" name="modules" value="1" style="width:10px">
</td>
<td align="left">xxx</td>
</tr>

</tbody>
</table>
</td>


webdriver selecting checkbox script is:

driver.findElement(By.xpath("//input[@name='modules' and @value='3']")).click(); 
driver.findElement(By.xpath("//input[@name='modules' and @value='2']")).click();    
driver.findElement(By.xpath("//input[@name='modules' and @value='1']")).click();
 

Monday, 17 February 2014

Button Click In Selenium Webdriver

1.if button type is

Html Code : <button type="submit"> Login </button>
path: driver.findElement(By.xpath("//button[@type='submit']")).click();

2.if button type is

Html Code : <input type="submit" value="SUBMIT" name="action"></input>
path:  driver.findElement(By.cssSelector("input[type='submit']")).click();

Friday, 29 November 2013

Selenium Webdriver Interview Questions With Answers

1.  What is webdriver?
 WebDriver is a simpler, more concise programming interface in addition to addressing some limitations in  the Selenium-RC API. Selenium-WebDriver was developed to better support dynamic web pages where elements of a page may change without the page itself being reloaded. WebDriver’s goal is to supply a well-designed object-oriented API that provides improved support for modern advanced web-app testing problems.
2.      What are the advantages of selenium2.0/webdriver?
    •         Need no server to start
    •     Easy to code
    •         Has sophisticated API to support wide verity of browsers.
    •     Supports to test dynamic UI web apps.

    3.      Difference between the selenium1.0 and selenium 2.0?
    Selenium 1.0
    Selenium 2.0/Webdriver
    1.      It ‘injected’ javascript functions into the browser when the browser was loaded and then used its javascript to drive the AUT within the browser.

    2.      Selenium server need to start to run tests
    3.      Has some loop-holes in supporting complex UI apps,Javascript security
    4.      No support for headless broswers
    1.      WebDriver makes direct calls to the browser using each browser’s native support for automation


    2.      Not needed unless tests are run on local machine.
    3.      Supports even drag and drop features and no security loop-holes
    4.      Supports htmlunit driver –headless browser runs fast



    4.      What are the Locators are there in selenium 2.0?
    It supports locators based on Id,name,xpath,dom,css,class,tagname
    5.      How to handle the Ajax Applications in Web driver?
    There are 2 types of waits webdriver supports to handle ajax applications to make webdrive sync to execution:
    Implicit wait :
    driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
    Explicit wait:   WebDriverWait, FluentWait
    WebElement strr = (new WebDriverWait(driver,30)).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[starts-with(@id,'yui_3_4_0_1_137509')]/ul/li[2]/a")));
    This link explains better about handling ajax in webdriver.

    5.      How to handle the multiple windows in web driver?
                driver.switchTo().window(Window ID);

    6.      Difference between findelement() and findelements()?
         findELement will find the first matching element.

         findELements will all the matching elements. You'll probably need to loop through all the elements  returned.
    7.      How to handle the alerts in web driver?
        driver.switchTo().alert().accept();
     
    8.      How to take the screen shots in seelnium2.0?
                File src2 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
                FileUtils.copyFile(src2,new File("d:\\sc2.jpeg"));
    9.      What is web driver architecture?
    Below link gives better idea of webdriver architecture:
    http://www.aosabook.org/en/selenium.html
    10.  What is the limitations of web driver?
    • Can not automate desktop applications, supports only web applications
    •  No inbuilt commands to generate good reports
    • Cannot support readily for new browsers

    Saturday, 19 October 2013

    Data Driven Testing in WebDriver Using jxl

    Data Driven Testing through WebDriver using jxl
    Prerequisite 
    1- Download jxl jar file and add it in to path
    2- Junit jar file
    3- Selenium-server-standalone-2.x.jar
    Add these three jar file in build path  .
    In general when we say Data Driven then only thing that should come in to mind is thatinput is going to be read from some xls file, xml,csv or some other table oriented file and might be output would also be written in xls,xml or csx file. All read data from various files are stored in variables and finally used by scripts to run the test cases.
    Data Driven testing is mainly divided in two part
    1- Reading data and storing in to variable
    2- Using data stored in variable in to some generic script.
    Reading Data and storing in to variableSince Webdriver don’t have structure like other automation tools like QTP to have its own Data table to store data to run tests in Data Driven framework. So we normally two jar file(Binaries) JXL(Java Excel API) and Apache POI to make Data Driven test framework for  WebDriver.
    I am using JXL binary in this example. so for reading data from xls file we need to follow these step
    1- Opening Excel file , so to open excel file we would use these two line. I have created one excel file r.xls and now we would write code to reach to this file and to open this excel sheet.
    import java.io.FileInputStream;
    import jxl.Workbook;
    FileInputStream fi = new FileInputStream(“C:\\Users\\kaushal\\Desktop\\r.xls”);
    Workbook w = Workbook.getWorkbook(fi);
    In above code
    FileInputStream obtains input bytes from a file in a file system
    2- Opening worksheet
    import jxl.Sheet;
    Sheet sh = w.getSheet(0); or w.getSheet(Sheetnumber)
    Here 0 as argument states about firest sheet, if we want to read second sheet then we may use 1 in place of 0
    3- Reading data
    code used is 
    String variable1 = s.getCell(column, row).getContents();
    These are 3 steps that is used in reading data from excel sheet
    In my example or code I am going to write code to test login to Gmail for various user and Username and Password is save in excel sheet and we will keep reading this data by using loop and we would store these data in two variable username and password
    package learing;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import jxl.JXLException;
    import jxl.Sheet;
    import jxl.Workbook;
    import jxl.read.biff.BiffException;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    public class Data{
    public static void main(String args[]) throws IOException, JXLException,BiffException,FileNotFoundException, InterruptedException{   
    WebDriver driver = new FirefoxDriver();
    Sheet s;
    
    FileInputStream fi = new FileInputStream("D:\\data1.xls");
    System.out.println("Brahmi");
    Workbook w = Workbook.getWorkbook(fi);
    s = w.getSheet(0);
    for(int row=1; row <=s.getRows();row++)
    {
    String username = s.getCell(0, row).getContents();
    System.out.println("Username "+username);
    driver.get("http://www.gmail.com");
    driver.findElement(By.name("Email")).sendKeys(username);
    String password= s.getCell(1, row).getContents();
    System.out.println("Password "+password);
    driver.findElement(By.name("Passwd")).sendKeys(password);
    Thread.sleep(10000);
    driver.findElement(By.name("signIn")).click();
     System.out.println("Waiting for page to load fully...");
    Thread.sleep(30000);
    }
    driver.quit();
    }
    
    }

    Angular JS Protractor Installation process - Tutorial Part 1

                         Protractor, formally known as E2E testing framework, is an open source functional automation framework designed spe...