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



Saturday, April 28, 2012

WebElements & Locators






WebElements & Locators


In WebDriver automation everything related with web elements as it is web application automation tool.


WebElement is nothing but, all DOM objects appeared in the web page. To do operations with DOM objects/ web elements we need to locate those elements exactly.


WebElement element=driver.findElement(By.<Locator>);


As we've seen in the above statement we have to specify some locator to identify web element.
'By' is the class, in that class we have different static methods to identify elements. Those are,
  1. By.className
  2. By.cssSelector
  3. By.id
  4. By.linkText
  5. By.name
  6. By.partialLinkText
  7. By.tagName
  8. By.xpath 

1. By.className
See below example
Example:1
  <td class=name> </td>
WebElement td=driver.findElement(By.className("name"));


2.By.cssSelector
CSS selector is the one the best ways to locate some complex elements in the page.

See below some examples for easy understanding
Example:1
 <td class=name> </td>
driver.findElement(By.cssSelector("td.name"));     In css selector we can denote class name with dot (.)
                             (or)
driver.findElement(By.cssSelector("[class=name]"))    We can specify the attribute name and its value.


Example:2
<input id=create>
driver.findElement(By.cssSelector("#create")).sendKeys("test");    shortcut for denoting id is #
                                  ( or )
driver.findElement(By.cssSelector("[id=create]")).sendKeys("test")


Example:3
<td value=dynamicValue_13232><td>
driver.findElement(By.cssSelector("[value*=dynamicValue]"))     * is for checking contained value
(here value contains dynamicValue)


Example:4
          <div value=testing name=dynamic_2307></div>
driver.findElement(By.cssSelector("[value=testing][name*=dynamic]"));  


If you want to include more attribute values in locator criteria use css locator as above. 




3. By.id
See below example
Example:1
  <td id=newRecord> </td>
WebElement td=driver.findElement(By.id("newRecord"));


here we can specify the id attribute value directly.


4. By.linkText
See below example
Example:1
  <a onclick=gotonext()>Setup </a>
WebElement link=driver.findElement(By.linkText("Setup"));


This is the best locator for locating links (anchor tags) in your web page.





5. By.partialLinkText
See below example
Example:1
  <a onclick=gotonext()>very long link text </a>
WebElement link=driver.findElement(By.partialLinkText("very"));
                               (or)
WebElement link=driver.findElement(By.partialLinkText("long link"));


This is the locator for locating links (anchor tags) using partial text it contains .


6. By.name
See below example
Example:1
  <td name=WebDriver> </td>
WebElement td=driver.findElement(By.name("WebDriver"));


7. By.tagName
See below example
Example:1
  <td class=name> </td>
WebElement td=driver.findElement(By.tagName("td"));


If you want to get the entire text of web page use below logic.


driver.findElement(By.tagName("body")).getText();


8. By.xpath
              
In next post I ll post about xpath locators in detail.




Thank you.









Tuesday, April 24, 2012

QTP Vs. Selenium


It is good news for all Selenium testers...!






Friday, April 20, 2012

Challenges of Test Automation






1. Selection of Automation Tool – Today there are n number of automation tools available in the market and choosing a good automation tool is one of the major challenges that an organization often faces. This is majorly because there are several commercial tools which are expensive, there are open source tools which might not be reliable and there are tools of which an organization may not have sufficient expertise to make optimum use of.

2. No Defined Process for Executing Automation Project within an organization – Automation is like a project execution ,wherein you start with Requirement, then you design the framework as per your requirements and finally you roll it out for Test Case Execution. Lack of systematic approach and process will make successful automation really tough. As we have processes, guidelines and checklist defined for our development project; we should also have guidelines, processes and checklist available for Automation as well.

3. Availability of Right Resources – The right set of resources is a must when you are doing automation. This means the resources should be skilled enough to design and code robust scripting, so that it requires minimum time for debugging during maintenance.

4. Commitment from Customer or Management – Automation is time consuming and resource intensive task. Customer or management commitment is required if one wants to get the real benefit of automation. This paper will highlight the approach wherein you can maximize your benefits within reasonable period of time.






Overcoming the Automation Challenges Using Selenium


Selenium is an Open Source Tool developed by ThoughtWorks. There are a set of Selenium tools which when combined provides you the power to automate simple to complex web application. Some of the Selenium Tool under ThoughtWorks umbrella are:

Selenium IDE – It is a Firefox add-on that makes it easy to record and playback tests in Firefox 2+. You can even use it to generate code to run the tests with Selenium Remote Control.

Selenium Remote Control (RC) – It is a client/server system that allows you to control web browsers locally or on other computers, using almost any programming language and testing framework.

Selenium Grid – It takes Selenium Remote Control to another level by running tests on many servers at the same time and cutting down on the time it takes to test multiple browsers or operating systems.

Bromine – It is a web-based QA tool of Selenium that enables you to easily run Selenium RC tests and view the results. It scales beautifully, from the single tester who just wants to run some tests without all the hassle; to the corporate solution, with multiple user-groups and hundreds of test cases.

Selenium is the best open source tool for doing automation for web based application and it does not have any cost attached to it. The only cost is the effort which will go for designing and developing the script for the application.

There is no need to define or develop separate Life Cycle for doing automation in Selenium. If you have an existing automation process, Selenium Automation Life Cycle will fit into that well. If you are using Selenium as an automation tool, you will find a lot of information online for the best process or Life Cycle to be adopted for automation.

Selenium scripting can be done in a number of programming languages like C#, Perl, PHP, Ruby, Java etc, unlike other commercial tools which support single scripting language. Since Selenium scripting can be done in any language of choice, one can easily find right resources for the programming language chosen for Selenium Automation.

Last but not the least, since this tool comes at ZERO PRICE, an organization’s management will find that the only investment they have made is on the infrastructure and human effort and not on the heavy licensing cost.




Thursday, April 19, 2012

JUnit Fundamentals






  • JUnit was created as a framework for writing automated, self-verifying tests in Java, which in JUnit are called test cases.
  • JUnit provides a natural grouping mechanism for related tests, which is called a test suite.
test case Vs TestCase class
  • test case generally refers to single test, verifying a specfic path through code.
  • To collect multiple test cases into a single class, itself a subclass of TestCase, with each test case implemented as a method on TestCase.
  • test case class is called fixture.
  • The TestCase class provides a default mechanism for identifying which methods are tests, but U can collect the tests urself in customized suites.
Points to Remember
  • As long as you follow a few simple rules, JUnit will find ur tests and execute them:
  • ur test methods must be instace level, take no parameteras, and return nothing. must declare them as a public void testMethodName().
  • The name of ur test method must start with 'test' all lowercase.
How To write simple JUnit
  • Create a subclass of TestCase
  • To create a test, write a method that expresses the test. Using a JUnit naming conventio that allows JUnit to find and execute ur test automatically.
  • U place the method in a class that extends the JUnit framework class TestCase.
  • To express how U expect the object to behave, you make assertions. (An assertion is simply a statement of ur expectation).
  • TestCase class is the center of the JUnit framework. TestCase in the package junit.framework.
TestSuite
  • A TestSuite is a Composite of Tests. It runs a collection of test cases.
  • A TestSuite can extract the tests to be run automatically. To do so you pass the class of your TestCase class to the TestSuite constructor.
TestCase
  • A test case defines the fixture to run multiple tests. To define a test case
  • implement a subclass of TestCase
  • define instance variables that store the state of the fixture
  • initialize the fixture state by overriding setUp()
  • clean-up after a test by overriding tearDown().
  • Each test runs in its own fixture so there can be no side effects among test runs.
Assertions
  • The class TestCase extends a utility class named Assert in the JUnit framework.
  • The Assert class provides the methods you will use to make assertions about the state of ur objects.
methods of Assert class is
  1. assertTrue(boolen condition)
  2. assertEquals(Object expected,object actual)
  3. assertEquals(int expected,int actual)
  4. assertSame(Object expected,object actual)
  5. assertNull(Object object).
Failure msgs
  • When assertion fails, it is worth including a short msg that indicates the nature of the failure, even a reason for it.
  • Each of the assertion methods accepts as an optional first parameter a String containing a msg to display when the assertion fails.
  • also assertion methods has its own customized failure msgs.
  • when an assertion fails, the assertion method throws an error: an assertionFailedError.
Failure Vs Error
  • JUnit throws an error rather than an expection because in Java, errors are unchecked:
  • When ur test contains a failed assertion, JUnit counts that as a failed test; but when ur test throws an expection(and does not catch it), JUnit counts that as an error.
Test has three basic parts
  1. Create objects.
  2. Invoke some objects.
  3. Check the results.
Note
  • In JUnit, the smallest unit of "test execution" is the test suite. JUnit doesn't actually execute individual tests,
  • but only executes test suites, so in order to execute ur test, U neeed to collect them into a test suite.
  • note that each test runs in its own instance of your test case class.
  • This is one of the fundamental aspects of JUnit's design.
TestResult
  • A TestResult collects the results of executing a test case. It is an instance of the Collecting Parameter pattern. 
  • The test framework distinguishes between failures and errors. 
  • A failure is anticipated and checked for with assertions.
  • Errors are unanticipated problems like an ArrayIndexOutOfBoundsException.
TestFailure
  • A TestFailure collects a failed test together with the caught exception.
How to create testsuite?
  • Create a method on ur test case class called suite(). IT must declared as public static Test suite(), taking no parameters and returning a Test object.
  • In the body of suite method, crete a TestSuite object, and then add Test objects to suite:(either individual tests or other test suites).
  • Return this TestSuite object.
==>manually building a test suite
TestSuite suite=new TestSuite();
suite.addTest(new MoneyTest("testEquals"));
suite.addTest(new MoneyTest("testSimpleAdd"));
==>Passing the TestCase class to TestSuite
return new TestSuite(MoneyTest.class);
  •  JUnit searches testCase class for declared methods that follows the rules.




Wednesday, April 18, 2012

Why & How WebDriver (Selenium) coding?






Why & How WebDriver automation?

The limitations of Selenium IDE are:
1) Selenium IDE uses only HTML language.
2) Conditional or branching statements execution like using of if, select statements is not possible.
3) Looping statements using is not possible directly in Selenium HTML language in ide.
4) Reading from external files like .txt, .xls is not possible.
5) Reading from the external databases is not possible with ide.
6) Exceptional handling is not there.
7) A neat formatted Reporting is not possible with IDE.


Selenium IDE is very useful in learning stage of Selenium as it has feature of record actions. we can export recorded test case to any of these formats.
Selenium IDE exporting formats
Download latest Selenium-server jar from here.
How to start with WebDriver ? (WebDriver + Java)
Create a Java project in eclipse
Create new Project
Select Java 
Give the Project name

Import downloaded selenium jar file in your java project.
Importing selenium jar in your project
To get above screen right click on your project
Build path > Configure Build path > Libraries (tab) > Add external Jar

Now entire setup is ready in your machine to write Selenium programs, Start writing your test cases using WebDriver classes & methods. WebDriver Java Document available here.

Example program : 

package org.openqa.selenium.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Selenium2Example  {
    public static void main(String[] args) {
        // Create a new instance of the Firefox driver
        // Notice that the remainder of the code relies on the interface, 
        // not the implementation.
        WebDriver driver = new FirefoxDriver();

        // And now use this to visit Google
        driver.get("http://www.google.com");
        // Alternatively the same thing can be done like this
        // driver.navigate().to("http://www.google.com");

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));

        // Enter something to search for
        element.sendKeys("Cheese!");

        // Now submit the form. WebDriver will find the form for us from the element
        element.submit();

        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());
        
        // Google's search is rendered dynamically with JavaScript.
        // Wait for the page to load, timeout after 10 seconds
        (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.getTitle().toLowerCase().startsWith("cheese!");
            }
        });

        // Should see: "cheese! - Google Search"
        System.out.println("Page title is: " + driver.getTitle());
        
        //Close the browser
        driver.quit();
    }
}

Happy coding... :)




Selenium.....






runs in many browsers and operating systems
can be controlled by many programming languages and testing frameworks.


What is Selenium?
Selenium automates browsers. That's it. What you do with that power is entirely up to you. Primarily it is for automating web applications for testing purposes, but is certainly not limited to just that. Boring web-based administration tasks can (and should!) also be automated as well.


Selenium has the support of some of the largest browser vendors who have taken (or are taking) steps to make Selenium a native part of their browser. It is also the core technology in countless other browser automation tools, APIs and frameworks.
If you want to


  • create robust, browser-based regression automation
  • scale and distribute scripts across many environments

Then you want to use Selenium WebDriver; a collection of language specific bindings to drive a browser -- the way it is meant to be driven.
Selenium WebDriver is the successor of Selenium Remote Control which has been officially deprecated.

Introducing WebDriver
The primary new feature in Selenium 2.0 is the integration of the WebDriver API. WebDriver is designed to providing an simpler, more concise programming interface along with 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.

How Does WebDriver ‘Drive’ the Browser Compared to Selenium-RC?
Selenium-WebDriver makes direct calls to the browser using each browser’s native support for automation. How these direct calls are made, and the features they support depends on the browser you are using. Information on each ‘browser driver’ is provided later in this chapter.
For those familiar with Selenium-RC, this is quite different from what you are used to. Selenium-RC worked the same way for each supported browser. It ‘injected’ javascript functions into the browser when the browser was loaded and then used its javascript to drive the AUT within the browser. WebDriver does not use this technique. Again, it drives the browser directly using the browser’s built in support for automation.








Tuesday, April 17, 2012

AdvancedUserInteractions API





The Advanced User Interactions API is a new, more comprehensive API for describing actions a user can perform on a web page. This includes actions such as drag and drop or clicking multiple elements while holding down the Control key.

How to :
In order to generate a sequence of actions, use the Actions generator to build it.


Actions builder = new Actions(driver);

   builder.keyDown(Keys.CONTROL)
       .click(someElement)
       .click(someOtherElement)
       .keyUp(Keys.CONTROL);
Then get the action:
      Action selectMultiple = builder.build();
And execute it:
   selectMultiple.perform();


Actions

Keyboard

The Keyboard interface has three methods:
  • void sendKeys(CharSequence... keysToSend) - Similar to the existing sendKeys(...) method.
  • void pressKey(Keys keyToPress) - Sends a key press only, without releasing it. Should only be implemented for modifier keys (Control, Alt and Shift).
  • void releaseKey(Keys keyToRelease) - Releases a modifier key.
It is the implementation's responsibility to store the state of modifier keys between calls. The element which will receive those events is the active element.

Mouse

The Mouse interface includes the following methods (This interface will change soon):
  • void click(WebElement onElement) - Similar to the existing click() method.
  • void doubleClick(WebElement onElement) - Double-clicks an element.
  • void mouseDown(WebElement onElement) - Holds down the left mouse button on an element.
  • Action selectMultiple = builder.build();
  • void mouseUp(WebElement onElement) - Releases the mouse button on an element.
  • void mouseMove(WebElement toElement) - Move (from the current location) to another element.
  • void mouseMove(WebElement toElement, long xOffset, long yOffset) - Move (from the current location) to new coordinates: (X coordinates of toElement + xOffset, Y coordinates of toElement + yOffset).
  • void contextClick(WebElement onElement) - Performs a context-click (right click) on an element.

Some Examples :

Mouse over Action : 
           new Actions(driver).moveToElement(element).perform();
Drag and Drop :
           new Actions(driver).dragAndDrop(dragable, dropAt).perform();

will update some more useful Actions here in future.