Showing posts with label Automation. Show all posts
Showing posts with label Automation. Show all posts

Saturday, April 6, 2013

Choosing options from Dropdown - WebDriver






In web application we see many drop down lists for many input fields (Ex : gender, age, country..etc). This drop down option is different from normal text/numeric input field. It has separate tag <select></select>in html.

In automation while filling most of the forms we need to fill/select the drop down values also. For achieving this WebDriver has separate class called Select.

In this post we will see what are all different method available in Select class.

Consider below example

                  HTML CODE
                                         <select id="city">
                                               <option value="Op1">Chennai</option>
                                               <option value="Op2">Hyderabad</option>
                                               <option value="Op3">Bangalore</option>
                                         </select>

Select an Option
Available methods for selecting an option are
  1. selectByIndex(int index)
  2. selectByValue(java.lang.String value)
  3. selectByVisibleText(java.lang.String text)
selectByIndex(int index)
Select the option at the given index.
Usage :
new Select(driver.findElement(By.id("city"))).selectByIndex(2);
In above example it will select the Hyderabad because it is in index 2.

selectByValue(java.lang.String value)
Select all options that have a value matching the argument.
Usage :
new Select(driver.findElement(By.id("city"))).selectByValue("Op3");
In above example it will select the Bangalore  based on the value attribute of that option.

selectByVisibleText(java.lang.String text)
Select all options that display text matching the argument.
Usage :
new Select(driver.findElement(By.id("city"))).selectByVisiableText("Chennai");
In above example it will select the Chennai based on the visible text.


De-select an option
Available methods for de-selecting an option(s) are,

  1. deselectAll()
  2. deselectByIndex(int index)
  3. deselectByValue(java.lang.String value)
  4. deselectByVisibleText(java.lang.String text)
deselectAll()
  • Clear all selected entries.
deselectByIndex(int index)
  • Deselect the option at the given index.
deselectByValue(java.lang.String value)
  • Deselect all options that have a value matching the argument.
deselectByVisibleText(java.lang.String text)
  • Deselect all options that display text matching the argument.


Getting all options
Some times we may in need to get all the options available in drop down list in that case below method will be useful.

  • getOptions();
getOptions()
It will return All options belonging to this select tag
Usage :
List<WebElement> allCities=new Select(driver.findElement(By.id("city"))).getOptions();
for(WebElement city:allCities)
{
      System.out.println(city.getText());    //It will return the text of each option
      System.out.println(city.getAttribute("value"));    //it will return the value attribute of each option
}

Get Selected Option(s)
If you want to verify whether the proper value got selected in particular drop down list you can make use of below methods.


  1. getFirstSelectedOption();
  2. getAllSelectedOptions() ;
getFirstSelectedOption();
  • The first selected option in this select tag (or the currently selected option in a normal select)
getAllSelectedOptions() ;
  • It will return List of All selected options belonging to this select tag. (This will be useful for multiselect picklist)

Handling multi-select pick list

                 HTML CODE
                                         <select id="city" multiple>
                                               <option value="Op1">Chennai</option>
                                               <option value="Op2">Hyderabad</option>
                                               <option value="Op3">Bangalore</option>
                                         </select>


Handling multi select pick list same as normal drop down( single pick list).
For selecting both Hyderabad, Bangalore option you need to use one of the below logics.

new Select(driver.findElement(By.id("city"))).selectByIndex(2);
new Select(driver.findElement(By.id("city"))).selectByIndex(3);
Or
new Select(driver.findElement(By.id("city"))).selectByvalue("Op2");
new Select(driver.findElement(By.id("city"))).selectByvalue("Op3");
Or
new Select(driver.findElement(By.id("city"))).selectByVisiableText("Hyderabad");
new Select(driver.findElement(By.id("city"))).selectByVisiableText("Bangalore");


I hope you understand WebDriver Select class usage in automation.


Happy Selecting :)


Regards,
SantoshSarma



Tuesday, March 26, 2013

Running JUnit test cases from cmd prompt





Running JUnit test cases from cmd prompt
For Running Junit 4.x test cases from command prompt you should use below command

java -cp C:\lib\junit.jar org.junit.runner.JUnitCore [test class name]

For running Junit 3.x test cases from command prompt you need use below command

java -cp /usr/java/lib/junit.jar junit.textui.TestRunner [test class name]

Example Program

TestCaseA.java

package test; import org.junit.Test; import org.junit.After; import org.junit.Before; public class TestCaseA { @Before public void beforeMethod() { System.out.println("Before method.."); } @Test public void JUnit4Test() { System.out.println("In test method"); } @After public void afterMethod() { System.out.println("after method"); } }

Execution from command prompt

java -cp junit-4.10.jar;test\TestCaseA.class; org.junit.runner.JUnitCore test.TestCaseA




Regards,
SantoshSarma J V




Friday, February 15, 2013

How to get auto populated Google search result?


Getting auto populated Google search result



Using below logic you can get the auto populated search result (Google search) for your search word

Logic
driver.get("http://www.google.co.in");  
 driver.findElement(By.name("q")).sendKeys("Test");  
 List<WebElement> autoPopulatedList=driver.findElements(By.cssSelector("tr>td>span"));  
 for(WebElement ele:autoPopulatedList)  
 {  
    System.out.println(e.getText());  
 }  



Example



Output of given code for above search word is 
selenium rc sendkeys
selenium puthon by
selenium
selenium tutorial
selenium  ide
selenium webdriver
selenium rc
selenium ide download
selenium grid
selenium documentation


Regards,
SantoshSarma

Passing parameters to TestCase using testng

Passing parameter using TestNg

  • Some times there is a need to send parameters (like browser name, browser version ..etc).
  • May be you want to run the same test case with different values for same attribute.
You can achieve above cases by using @parameter annotation in testng

Below is the example for running same test cases in different browsers (firefox, chrome) by passing different parameters (browser name, version, profile)

TestNg Class
import org.openqa.selenium.WebDriver;  
   import org.testng.annotations.Parameters;  
   import org.testng.annotations.Test;  
   import org.testng.annotations.BeforeMethod;  
   import org.testng.annotations.AfterMethod;  
   import org.testng.annotations.BeforeClass;  
   import org.testng.annotations.AfterClass;  
   import org.testng.annotations.BeforeTest;  
   import org.testng.annotations.AfterTest;  
   public class ExampleTestCase   
   {  
     private static WebDriver driver;
     @Parameters({"browser,version"})
     @BeforeClass
     public void beforeClass(String browser,String version,String profile)
     {
          driver=getDriverInstance(browser,version,profile);
     }
     @BeforeTest
     public void beforeTest()
     {
     }  
     @Test
     public void f()
     {
          //your test code here
     }
   @AfterTest
    public void afterTest()
    {
    }
    @AfterClass
    public void afterClass()
    {
        driver.quit();
    }
}

getDriverInstance method implimentation
public static WebDriver getDriverInstance(String browser,String version,String profile)  
  {  
     WebDriver driver=null;  
     if(browser.equals("firefox"))  
     {  
       DesiredCapabilities capability = DesiredCapabilities.firefox();  
       capability.setVersion(version);
       capability.setCapability(FirefoxDriver.PROFILE, profile);
       driver = new FirefoxDriver(capability);  
     }  
     else if(browser.equals("chrome"))  
     {  
         DesiredCapabilities capability = DesiredCapabilities.chrome();  
         capability.setVersion(version);  
         driver = new ChromeDriver(capability);  
     }  
     return driver;  
  }  

TestNg Suite
<?xml version="1.0" encoding="UTF-8"?>  
   <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">  
   <suite thread-count="2" name=MyTestSuite" parallel="tests">  
       <test name="RunInFirefox" preserve-order="false">
          <parameter name="browser" value="firefox">
          <parameter name="version" value="8"/>
          <parameter name="profile" value="default">
                <classes preserve-order="true">  
                      <class name="com.test.TestCase1"/>  
                      <class name="com.test.TestCase2"/>  
                      <class name="com.test.TestCase3"/>  
                </classes>  
       </test>  
       <test name="RunInChrome" preserve-order="false">
          <parameter name="browser" value="chrome">
          <parameter name="version" value="21"/>  
               <classes preserve-order="true">  
                    <class name="com.test.TestCase1"/>  
                    <class name="com.test.TestCase2"/>  
                    <class name="com.test.TestCase3"/>  
               </classes>  
        </test>  
</suite>  



Related Topics
Running Junit Cases from command prompt
Upload photo in facebook using webdriver

Friday, February 1, 2013

Uploading photo in facebook using WebDriver

Automate Facebook with WebDriver
Uploading photo in facebook

driver.get("http://www.facebook.com");  
  driver.findElement(By.id("email")).clear();  
  driver.findElement(By.id("email")).sendKeys("*******@gmail.com");  
  driver.findElement(By.id("pass")).clear();  
  driver.findElement(By.id("pass")).sendKeys("*******");  
  driver.findElement(By.cssSelector("#loginbutton > input")).click();  
  driver.findElement(By.linkText("Facebook")).click();  
  driver.findElement(By.linkText("Add Photos/Video")).click();  
  driver.findElement(By.xpath("//div[text()='Upload Photos/Video']/
                           following-sibling::div/input")).sendKeys("C:\\MyPhoto.jpg");  

Tuesday, January 29, 2013

WebDriver waits


Web application automation is depends on so many factors. Browser, network speed ...etc. We should write unquie code for running in all environments. For achieveing that we need to wait for WebElements before performing any operation on that.

Here we will see some built-in waits in WebDriver.

implicitlyWait

1WebDriver driver = new FirefoxDriver();
2driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
3driver.get("http://www.google.co.in");
4WebElement myElement = driver.findElement(By.id("someId"));
Implicit waits are basically your way of telling WebDriver the latency that you want to see if specified web element is not present that WebDriver looking for. (Click here for more information). This will be useful when certain elements on the webpage will not be available immediately and needs some time to load.

pageLoadTimeout

1driver.manage().timeouts().pageLoadTimeout(30, SECONDS);
Sets the amount of time to wait for a page load to complete before throwing an error. If the timeout is negative, page loads can be indefinite.

setScriptTimeout

1driver.manage().timeouts().setScriptTimeout(30,SECONDS);

Sets the amount of time to wait for an asynchronous script to finish execution before throwing an error.


Regards,
SantoshSarma

Monday, January 28, 2013

isTextPresent() ? In WebDriver

While automation web applications in some places we want/need to check particular text is present or not.

In WebDriver (Selenium 2), there is no predefined method for checking this. (In Selenium-RC isTextPresent("text") built-in method exist ) So we need to implement our own method to achieve this.


Let us consider you are searching for text "WebDriver"



boolean isTextPrest=false;

Method-1
 isTextPrest=driver.findElement(By.tagName("body")).getText().contains("WebDriver");  

Method-2
 isTextPrest=driver.findElement(By.xpath("//*[contains(.,'WebDriver')]")).isDisplayed();  

Method-3
 Selenium sel=new WebDriverBackedSelenium(driver, "");  
 isTextPresent=sel.isTextPresent("WebDriver");  


FYI : Method-1 will take more time than remaining (comparatively)

Happy Coding :)


Regards,
SantoshSarma

XPath indexing

Q : What does //td[2] mean?
A : All td elements in that page (document), that are second child of their parent.


Q : Will //td[2] return only one element?
A :  No, there may be many such elements. (second child td of their parent)


 if you've any doubts regarding this xpath indexing post it in comments section.



Related Topics
How to write xpath?
Locating elements using xpath




Tuesday, January 22, 2013

Finding elements within iframe using firebug


Firebug Tip

Firebug command line allows executing JavaScript expressions within context of the current page. Firebug also provides a set of built in APIs and one of them is cd().

Lets consider below iframe

                <iframe id="testID" name="testName" src="iframe.html" />


  • cd(document.getElementById("testID").contentWindow); switch to a frame by ID
  • cd(window.frames[0]); switch to the first frame in the list of frames
  • cd(window.frames["testName"]); switch to a frame using by name
  • cd(window.top); switching back to the top level window


Happy Coding .. :)


Regards,
SantoshSarma

Thursday, January 3, 2013

isElementPresent? Method another way





“we can use the findElements() call, and then we just need to check that the size of the list returned is 0.

You can write logic like this.

List elements = driver.findElements(By.Id("element id"));
if(elements.size()==0)
        No element found
else
        Element found



Monday, November 19, 2012

How to take screen shot ?

Do you want to take screenshots while automation running? TakesScreenshot interface for capturing a screenshot
of a web page. If take Screenshot when en exception or failure occurred then it will be easy to pin point issue. We can also take screenshot for verifying values, text in webPage.

Using below method you can take screenshots while running the automation.

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.TakesScreenshot;

 public static void takeScreenShot(WebDriver driver,String fileName)  
      {  
           try {  
                File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);  
                FileUtils.copyFile(scrFile, new File("C:\\"+fileName+".png"));  
           }   
           catch (Exception e) {  
                e.printStackTrace();  
           }  
      }  

Saturday, October 13, 2012

Implicit wait Vs. Explicit wait

WebDriver Waits
Implicit wait

WebDriver driver = new FirefoxDriver();  
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Implicit waits are basically your way of telling WebDriver the latency that you want to see if specified web element is not present that WebDriver looking for. So in this case, you are telling WebDriver that it should wait 10 seconds in cases of specified element not available on the UI (DOM).


  • Implicit wait time is applied to all elements in your script



Explicit wait (By Using FluentWait)

public static WebElement explicitWait(WebDriver driver,By by)  
{  
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)  
             .withTimeout(20, TimeUnit.SECONDS)  
             .pollingEvery(2, TimeUnit.SECONDS)  
             .ignoring(NoSuchElementException.class); 

     WebElement element= wait.until(new Function<WebDriver, WebElement>() {  
           public WebElement apply(WebDriver driver) {  
             return driver.findElement(By.id("foo"));  
            }  
      });  
  return 


Explicit waits are intelligent waits that are confined to a particular web element. Using explicit waits you are basically telling  WebDriver at the max it is to wait for X units of time before it gives up.

  •  In Explicit you can configure, how frequently (instead of 2 seconds) you want to check condition
  • Explicit wait time is applied only for particular specified element.
Explicit wait

public static WebElement explicitWait(WebDriver driver,By by)  
 {  
      WebDriverWait wait = new WebDriverWait(driver, 30);  
      wait.until(ExpectedConditions.presenceOfElementLocated(by));  
 }       

In above method it will wait until either ExpectedConditions become true or Timeout (30 sec).

Friday, August 10, 2012

Google Doodle Hurdles


I hope everyone played this hurdles on Google doodle here . 
Post your best scores here and guess why I've posted this here.

Happy weekend 

Regards,
SantoshSarma

Friday, July 20, 2012

How not to automate..!


       Whatever you do, do not simply distribute a testing tool among your testers and expect them to automate the test process. Just as you would never automate accounting by giving a program compiler to the accounting department, neither should you attempt to automate testing by just turning a testing tool over to the test group.
   It is important to realize that test automation tools are really just specialized programming languages, and developing an automated test library is a development project requiring commensurate skills.


Automation is more than capture/replay
If you acquired a test tool with the idea that all you have to do is record and playback the tests, you are due for disappointment. Although it is the most commonly recognized technique, capture/replay is not the most successful approach. Selecting an Automation Approach, capture and replay does not result in a test library that is robust, maintainable or transferable as changes occur.


Don’t write a program to test a program!
The other extreme from capture/replay is pure programming. But if you automate your tests by trying to write scripts that anticipate the behavior of the underlying program and provide for each potential response, you will essentially end up developing a mirror version of the application under test! Where will it end? Who tests the tests? Although appealing to some, this strategy is doomed - no one has the time or resources to develop two complete systems.   Ironically, developing an automated test library that provides comprehensive coverage would require more code than exists in the application itself! This is because tests must account for positive, negative, and otherwise invalid cases for each feature or function.


Duplication of effort
The problem is, if you just hand an automation tool out to individual testers and command that they automate their tests, each one of them will address all of these issues - in their own unique and Introduction personal way, of course. This leads to tremendous duplication of effort and can cause conflict when the tests are combined, as they must be.


Automation is more than test execution
So if it isn’t capture/replay and it isn’t pure programming, what is it? Think of it this way. You are going to build an application that automates your testing, which is actually more than just running the tests. You need a complete process and environment for creating and documenting tests, managing and maintaining them, executing them and reporting the results, as well as managing the test environment. Just developing scores of individual tests does not comprise a strategic test automation system.



Need for a framework
Instead, approach the automation of testing just as you would the automation of any application - with an overall framework, and an orderly division of the responsibilities. This framework should make the test environment efficient to develop, manage and maintain. 

Remember, test tools aren’t magic - but, properly implemented, they can work wonders!

Saturday, July 14, 2012

isElementPresent ?

Selenium RC we became quite used to using methods like iSElementPresent and waitForCondition/waitForPageToLoad to deal with Ajax and page loading events. With WebDriver we have to write them ourselves.


There are 4 important things going on here. In order:
  1. Setting implicity_wait to 0 so that WebDriver does not implicitly wait.
  2. Returning True when the element is found.
  3. Catching the NoSuchElementException and returning False when we discover that the element is not present instead of stopping the test with an exception.
  4. Setting implicitly_wait back to 10 after the action is complete so that WebDriver will implicitly wait in future.
Method
 isElementPresent(WebDriver driver,By by)  
 {  
    driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);  
    try  
    {  
       driver.findElement(by);  
       return true;  
    }  
    catch(Exception e)  
    {  
       return false;  
    }  
    finally  
    {  
       driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);  
     }  
 }  


Regards,
Santosh.

How to write Xpath ?





How to write Xpath?
In Selenium-Rc/WebDriver automation xpath is the one of the way to locate elements on webpage.XPath uses path expressions to select nodes/element in an XML/ HTML document.

How to verify in firebug?
  • Open firebug in firefox/Chrome.
  • Go to console.
  • type : $x("<xpath>").
  • Hit Enter.
  • If it is correct path you can element in that console. If you mouse hover on that, the element will highlight in web page.
Example:


How to write Xpath?
Examples
Facebook signup form
1. Select first name
 //input[@id='firstname]     OR       //input[@name=firstname]   
In this case no need of xpath locator because we can use By.id, By.name,By.cssSelector.
By.id("firstname")    |   By.name("firstname")  | By.cssSelector("[id=firstname]")

2. Selecting first name input using First Name label
 //label[text()='First Name:']/parent::td/following-sibling::td/div/input  
                          or  
      //label[text()='First Name:']/../../td/div/input  
In above example,
parent This keyword helps you to back track to parent node from child node.
following-sibling This keyword helps you to go following-sibling.
preceding-sibling This keyword helps you to go preceding-sibling.
.. This also helps you to go parent node from child node
See below table for more keywords
3. Using contains, starts-with

Select Last Name using contains //label[contains(text(),'Last')]/../../td/div/input
Select Last Name using starts-with //label[starts-with(text(),'Last')]/../../td/div/input

4. Index/position based

5. Some more expressions


If you have any doubts in xpath..Post your html code snippet here I would try to give you solution.


Happy Coding..! 

Regards,
Santosh