Selenium

Overview

Selenium is a tool that employs Javascript in order to take control over your browsers and simulate web surfing activities. Therefore, Selenium is able to replicate any action typically undertaken by a user, such as clicking, typing and retrieving data from web pages.

When combining Selenium with other testing frameworks such as JUnit or TestNG, you are getting a very powerful and complete testing framework for web applications.

Selenium is comprised of 3 main components: Selenium IDE, Selenium Remote Control(RC) and Selenium Grid.

  • Selenium IDE is a plugin for the Firefox browser. It records your actions(clicks, characters typed, etc) on Firefox in order to replay them in the same sequence. As a result, by adding some validations, you can easily create tests through "point and click". It is also able to export recorded tests in different programming languages that can be run by Selenium RC.
  • Selenium Remote Control(RC) is a client and server system that offers the same basic functionalities as Selenium IDE in addition to its own unique features. Due to its design, it is much more flexible and versatile than Selenium IDE. Hence, it supports multiple browsers(e.g. Internet Explorer, Firefox, Opera, Safari, etc) and multiple programming languages(e.g. Java, .Net, PHP, Ruby, Python, Perl, JavaScript, etc). However, flexibility comes at a price. You no longer have the "point and click" luxury of the Selenium IDE. You have to manually write all the codes in order to tell Selenium which actions should be taken on your browser.
  • Selenium Grid allows you to run tests on multiple computers and/or multiple browsers concurrently. Therefore, it reduces the time required to run your tests.

Using Selenium IDE is the easiest way to understand Selenium. Most new users will use it as the entry point and subsequently migrate to Selenium RC for more complex testing and to obtain the support of their full blown programming language of choice.

Limitations

  • Selenium was not designed to do performance/load testing.
  • Selenium is using Javascript to control the browser. Therefore, whatever Javascript can't do, Selenium can't do. For example, it can't control the pop-up window that shows up when you are trying to download a file. However, if you are using Firefox, then you can circumvent this by changing the settings in Firefox to allow direct file saving without the download window acting as an intermediary.

Usage

Here are typical cases where Selenium is used:

  • Functional Testing
  • Browser Compatibility Testing

First Selenium application in Java

The following shows you step-by-step how to run your first Selenium RC application in Java.

  1. It is assumed that you have JDK installed and set in your computer. If you are getting the version number(e.g javac 1.6.0_06) by running the following command in the Command Prompt, then your Java Compiler is installed and set correctly.
    javac -version
  2. Download Selenium RC.
  3. Decompress Selenium RC. In my case, I decompress it to C:\.
  4. From the Command Prompt, go to the directory where selenium-server.jar is located.
    cd C:\selenium-remote-control-1.0-beta-1\selenium-server-1.0-beta-1\
    Then execute the following command to launch Selenium Server:
    java -jar selenium-server.jar -interactive
    The previous command will start Selenium Server. It should look similar to the following:
    15:55:51.004 INFO - Java: Sun Microsystems Inc. 10.0-b22
    15:55:51.004 INFO - OS: Windows XP 5.1 x86
    15:55:51.004 INFO - v1.0-beta-1 [2201], with Core v1.0-beta-1 [1994]
    15:55:51.084 INFO - Version Jetty/5.1.x
    15:55:51.084 INFO - Started HttpContext[/selenium-server/driver,/selenium-server/driver]
    15:55:51.084 INFO - Started HttpContext[/selenium-server,/selenium-server]
    15:55:51.084 INFO - Started HttpContext[/,/]
    15:55:51.104 INFO - Started SocketListener on 0.0.0.0:4444
    15:55:51.104 INFO - Started org.mortbay.jetty.Server@13e205f
    Entering interactive mode... type Selenium commands here (e.g: cmd=open&1=http://www.yahoo.com)
  5. The Google.java file containing the Java code below is our first Selenium RC application. What the code does is to launch Internet Explorer, open Google webpage and then search for Selenium RC.
    /**
     * Google.java
     * Open Google webpage and search for "Selenium RC".
     * @Author: Xuan Ngo
     */
    import com.thoughtworks.selenium.DefaultSelenium;
     
    public class Google
    {
      public static void main(String[] args)
      {
        final String sServerHost  = "localhost";
        final int iServerPort     = 4444;
        final String sBrowserType = "*iexplore"; // For Firefox, use *firefox
        final String sBaseUrl     = "http://www.google.ca/";
     
        DefaultSelenium oDefaultSelenium = new DefaultSelenium(sServerHost, iServerPort, sBrowserType, sBaseUrl);
        oDefaultSelenium.start();           // Start Selenium.
        oDefaultSelenium.setSpeed("5000");  // Wait 5 seconds for every instructions so that you can see what Selenium is doing.
     
        // Open the main google webpage.
        oDefaultSelenium.open("http://www.google.ca/index.html"); 
     
        // Type "Selenium RC" into the search input field.
        oDefaultSelenium.type("name=q", "Selenium RC"); // Use name locator to identify the search input field.
     
        // Click on "Google Search" button
        oDefaultSelenium.click("xpath=//input[@name='btnG']");
     
        // Close the browser.
        oDefaultSelenium.stop();
      }
    }
    Execute the command below to compile the Java code.
    javac -classpath C:\selenium-remote-control-1.0-beta-1\selenium-java-client-driver-1.0-beta-1\selenium-java-client-driver.jar Google.java
     
    Note: You have to change C:\selenium-remote-control-1.0-beta-1\selenium-java-client-driver-1.0-beta-1\selenium-java-client-driver.jar to match the path where you put your selenium-java-client-driver.jar.
  6. Execute the command below to run our application.
    java -classpath C:\selenium-remote-control-1.0-beta-1\selenium-java-client-driver-1.0-beta-1\selenium-java-client-driver.jar;. Google
     
    Note: You have to change C:\selenium-remote-control-1.0-beta-1\selenium-java-client-driver-1.0-beta-1\selenium-java-client-driver.jar to match the path where you put your selenium-java-client-driver.jar.
AttachmentSize
File Google.java1.14 KB

Locators

In order for Selenium to control and manipulate each HTML element(e.g. <a>, <input>, <div>, etc) on the website, you have to provide it with a reference to each element. That reference is used by Selenium to identify the element and apply the actions on that element. The term used in Selenium to denote the reference of an element is called locator.

There are different types of locators. For the complete list, see the documentation of Selenium. The following are the most commonly used types of locators:

id=id
Refer to the element with the specified @id attribute.
HTML:
<div id="unique_logo_id"></div>
----------------------------------------
Locator:
id=unique_logo_id
name=name
Refer to the element with the specified @name attribute.
HTML:
<input name="first_name" />
----------------------------------------
Locator:
name=first_name
xpath=xpathExpression
Refer to the element with the specified Xpath expression.
HTML:
<table>
    <tbody>
        <tr><td>cell1</td></tr>
        <tr><td id="cell_id_2">cell2</td></tr>
    </tbody>
</table>
----------------------------------------
Locator:
xpath=//table/tbody/tr/td[text()='cell2']
xpath=//*[@id='cell_id_2']
xpath=//td[text()='cell2']
xpath=//td[contains(text(), '2')]
link=textPattern
Refer to a link with the specified text pattern.
HTML:
<a href="page2.html">Next</a>
----------------------------------------
Locator:
link=Next
link=regexp:[nN][eE][xX][tT]
link=regexpi:NEXT

By default, if the type of locator is not explicitly specified, Selenium will assume that it is an @id. If no match is found, then it will assume that it is a @name.

Therefore, given that you provide the locator of the desired element, Selenium will be able to click or type on that element, retrieve text from that element, etc. Most of the functions provided by Selenium use locator. Hence, it is important that you master the locator in order to be able to use Selenium efficiently.

Click on link

/**
 * Click on a simple link(e.g Next)
 * Assume that you have Internet Explorer and Selenium Server is running on your
 *  computer on default port 4444. Otherwise, change accordingly in the constructor.
 * @Author: Xuan Ngo
 */
import com.thoughtworks.selenium.DefaultSelenium;
 
public class ClickSimple
{
  private DefaultSelenium m_oBrowser = null;
 
  public static void main(String[] args)
  {
    ClickSimple oClickSimple = new ClickSimple();
 
    // Click on Next link.
    oClickSimple.runExamples();
  }
 
  // Constructor
  public ClickSimple()
  {
    this.m_oBrowser = new DefaultSelenium("localhost", 4444, "*iexplore", "http://openwritings.net/");
    this.m_oBrowser.start(); // Start Selenium.
    this.m_oBrowser.open("http://openwritings.net/sites/default/files/clickLinkTest.html"); // Open the webpage.
  }
 
  // Click on Next link.
  public void runExamples()
  {
    this.m_oBrowser.click("link=Next"); // Click on Next link.
 
    //this.m_oBrowser.stop(); // Close Selenium.
  }
}
AttachmentSize
HTML icon clickLinkTest.html146 bytes
HTML icon clickLinkTest_result.html131 bytes

Click on any html element using different locators

/**
 * Click on any html element in the webpage as long as you can use the locators to identify them.
 * Assume that you have Internet Explorer and Selenium Server is running on your
 *  computer on default port 4444. Otherwise, change accordingly in the constructor.
 * @Author: Xuan Ngo
 */
import com.thoughtworks.selenium.DefaultSelenium;
 
public class ClickAny
{
  private DefaultSelenium m_oBrowser = null;
 
  public static void main(String[] args)
  {
    ClickAny oClickAny = new ClickAny();
 
    // Click on any html element in the webpage.
    oClickAny.runExamples();
  }
 
  // Constructor
  public ClickAny()
  {
    this.m_oBrowser = new DefaultSelenium("localhost", 4444, "*iexplore", "http://openwritings.net/");
    this.m_oBrowser.start(); // Start Selenium.
    this.m_oBrowser.open("http://openwritings.net/sites/default/files/ClickAnyElementExample.html"); // Open the webpage.
  }
 
  // Click on any html element in the webpage.
  public void runExamples()
  {
    // Click on Submit button using NAME locator.
    this.m_oBrowser.click("name=submit_button"); 
 
    // Click on <li> using ID locator.
    this.m_oBrowser.click("id=unique-link-id");
 
    // Click on <li> using XPATH locator.
    this.m_oBrowser.click("xpath=//li[contains(text(), 'using the xpath')]"); 
 
    //this.m_oBrowser.stop(); // Close Selenium.
  }
}
AttachmentSize
HTML icon ClickAnyElementExample.html1.24 KB

Type characters

/**
 * Type characters.
 * Assume that you have Internet Explorer and Selenium Server is running on your
 *  computer on default port 4444. Otherwise, change accordingly in the constructor.
 *  You need to change the encoding of your editor to support the Chinese characters below.
 * @Author: Xuan Ngo
 */
import com.thoughtworks.selenium.DefaultSelenium;
 
public class WritingExample
{
  private DefaultSelenium m_oBrowser = null;
 
  public static void main(String[] args)
  {
    Writing oWriting = new Writing();
 
    // Type characters.
    oWriting.runExamples();
  }
 
  // Constructor
  public Writing()
  {
    this.m_oBrowser = new DefaultSelenium("localhost", 4444, "*iexplore", "http://openwritings.net/"); // *iexplore, *firefox 
    this.m_oBrowser.start(); // Start Selenium.
    this.m_oBrowser.open("http://openwritings.net/sites/default/files/type.html"); // Open the webpage.
  }
 
  // Type characters.
  public void runExamples()
  {
    // Type characters using different locators and field types.
    this.m_oBrowser.type("xpath=//*[@name='first-name']", "Xuan");  // XPATH locator.
    this.m_oBrowser.type("css=input[name=last-name]", "Ngo");       // CSS locator.
    this.m_oBrowser.type("dom=document.getElementsByName('my-password').item(0)", "my password"); // DOM locator.
    this.m_oBrowser.type("xpath=//*[@name='chinese-chars']", "中文");// Type Chinese characters. You need to change the encoding of your editor.
 
 
    // Simulates keystroke events on the specified element, as though you typed the value key-by-key.
    // "auto complete" = a,u,t,o, ,c,o,m,p,l,e,t,e
    this.m_oBrowser.typeKeys("css=input[name=key-press]", "auto complete"); // CSS locator.
 
    //this.m_oBrowser.stop(); // Close Selenium.
  }
}

Check radio buttons and checkboxes

/**
 * Un/Check radio buttons and checkboxes.
 * Assume that you have Internet Explorer and Selenium Server is running on your
 * computer on default port 4444. Otherwise, change accordingly in the constructor.
 * @Author: Xuan Ngo
 */
import com.thoughtworks.selenium.DefaultSelenium;
 
public class Check
{
  private DefaultSelenium m_oBrowser = null;
 
  public static void main(String[] args)
  {
    Check oCheck = new Check();
 
    // Un/Check radio buttons and checkboxes.
    oCheck.runExamples();
  }
 
  // Constructor
  public Check()
  {
    this.m_oBrowser = new DefaultSelenium("localhost", 4444, "*iexplore", "http://openwritings.net/");
    this.m_oBrowser.start(); // Start Selenium.
    this.m_oBrowser.open("http://openwritings.net/sites/default/files/radio_checkbox.html"); // Open the webpage.
  }
 
  // Un/Check radio buttons and checkboxes.
  public void runExamples()
  {
    // Radio Button: Check Monday using XPATH locator.
    this.m_oBrowser.check("xpath=//input[@value='Mon']"); 
 
    // Checkbox: Uncheck Apple using CSS selector.
    this.m_oBrowser.uncheck("css=input[name='apple']"); 
 
    // Checkbox: Check Orange using CSS selector.
    this.m_oBrowser.check("css=input[name='orange']"); 
 
    //this.m_oBrowser.stop(); // Close Selenium.
  }
}
AttachmentSize
HTML icon radio_checkbox.html1.24 KB

Select single/multiple options

/**
 * Select single/multiple options.
 * Assume that you have Internet Explorer and Selenium Server is running on your
 *  computer on default port 4444. Otherwise, change accordingly in the constructor.
 * @Author: Xuan Ngo
 */
import com.thoughtworks.selenium.DefaultSelenium;
 
public class Select
{
  private DefaultSelenium m_oBrowser = null;
 
  public static void main(String[] args)
  {
    Select oSelect = new Select();
 
    // Select single/multiple options.
    oSelect.runExamples();
  }
 
  // Constructor
  public Select()
  {
    this.m_oBrowser = new DefaultSelenium("localhost", 4444, "*iexplore", "http://openwritings.net/");
    this.m_oBrowser.start(); // Start Selenium.
    this.m_oBrowser.open("http://openwritings.net/sites/default/files/select.html"); // Open the webpage.
  }
 
  // Select single/multiple options.
  public void runExamples()
  {
    // Single Selection: Use ID locator and LABEL option locator to select July.
    this.m_oBrowser.select("id=single-selection", "label=July"); 
 
    // Multiple Selections: Use variations of locators to select February, August and November.
    this.m_oBrowser.select("xpath=//select[@size='12']", "value=Feb");                             // Select February
    this.m_oBrowser.addSelection("css=select[id=multi-selections]", "index=7");                    // and August.
    this.m_oBrowser.addSelection("dom=document.getElementById('multi-selections')", "id=m_opt_10");// and November.
 
    //this.m_oBrowser.stop(); // Close Selenium.
  }
}
AttachmentSize
HTML icon select.html1.8 KB

Misuse of waitForPageToLoad()

The common mistake that people usually do is to use waitForPageToLoad() function to wait for what appears to be a webpage being loaded. But, in fact, it is Ajax or JavaScript that is doing some changes to a portion of the webpage. As a result, the waitForPageToLoad() function will always time out because it is expecting for the whole webpage to load that never happened.

So, the next time that you get a time out on waitForPageToLoad() function even though that you swear you have allocated more than enough time to it, then you are not using waitForPageToLoad() function correctly. A simple trick to know is to replace the waitForPageToLoad() function with a pause. If Selenium is able to execute the next instruction, then you shouldn't use the waitForPageToLoad() function. Perhaps, you should consider to write a new function to wait for what you expected.

Speed benchmark of locators

Selenium locators are not all equals. Some locators are faster than others. Therefore, I took up the task to measure the speed of each Selenium locators. The speed test that I did is to measure the time that each locator took to fill up the 1st 50 input fields of the 500 inputs fields. From the results, ID locator is the fastest.

The Xpath locator is always faster in Firefox than in Internet Explorer because Internet Explorer doesn't have a native Xpath support. Therefore, Selenium is using ajaxslt library when it handles Xpath in Internet Explorer.

Results of the speed benchmark

SUMMARY: *firefox2 [5 tries]
=========================
                 ID Avg. =    805.2 ms   (id=idX)                      
               NAME Avg. =   2273.2 ms   (name=nameX)                  
       CSS_SELECTOR Avg. =   2974.2 ms   (css=input[name="nameX"])     
     RELATIVE_XPATH Avg. =    907.2 ms   (xpath=//input[@name='nameX'])
     ABSOLUTE_XPATH Avg. =    773.0 ms   (xpath=/html/body/input[X])   
 NAME_AS_IDENTIFIER Avg. =   2377.2 ms   (identifier=nameX)    
 
SUMMARY: *iexplore7 [5 tries]
=========================
                 ID Avg. =   2103.0 ms   (id=idX)                      
               NAME Avg. =  42913.8 ms   (name=nameX)                  
       CSS_SELECTOR Avg. =   5724.4 ms   (css=input[name="nameX"])     
     RELATIVE_XPATH Avg. =  59996.2 ms   (xpath=//input[@name='nameX'])
     ABSOLUTE_XPATH Avg. =  26494.0 ms   (xpath=/html/body/input[X])   
 NAME_AS_IDENTIFIER Avg. =  41917.8 ms   (identifier=nameX)     

Codes used to measure the speed of locators

Before you run the code below, you have to put SeleniumData.html in the root directory of your webserver. And in the code, you may have to change localhost to your correspondent host.

/**
 * Benchmark the speeed of different Selenium locators.
 * - Put SeleniumData.html in the root directory of your webserver
 * - You may have to change localhost to your correspondent host.
 * @Author: Xuan Ngo
 */
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
 
import java.util.Calendar;
import java.util.Formatter;
 
import com.thoughtworks.selenium.DefaultSelenium;
 
public class LocatorsBenchmark
{
 
  public static void main(String[] args) 
  {
    LocatorsBenchmark oLocatorsBenchmark = new LocatorsBenchmark();
 
    /**
     * Generate test data.
     * SeleniumData.html should be put in the root directory 
     *  of your web server.
     */
    final String sFilename = "SeleniumData.html";
    final int iMaxInputsFields = 500;
    oLocatorsBenchmark.generateData(sFilename, iMaxInputsFields);
 
    /*******************************
     * Benchmark process start here.
     *******************************/
    final int iMaxFillInput = 50;
    final int iTry = 5;
 
    long lId              = 0;
    long lName            = 0;
    long lRelativeXpath   = 0;
    long lAbsoluteXpath   = 0;
    long lNameAsIdentifier= 0;
    long lCssSelector     = 0;
 
    final String[] aBrowserTypes = {"*firefox", "*iexplore"};
    for(int j=0; j<aBrowserTypes.length; j++)
    {
      final String sBaseUrl = "http://localhost";
      final String sUrl = "http://localhost/SeleniumData.html";
      final String sBrowserType = aBrowserTypes[j];
      for(int i=0; i<iTry; i++)
      {
        System.out.println(sBrowserType+":  Try "+i);
        lId               += oLocatorsBenchmark.fillData(iMaxFillInput, LocatorsBenchmark.ID, sBaseUrl, sUrl, sBrowserType);
        lName             += oLocatorsBenchmark.fillData(iMaxFillInput, LocatorsBenchmark.NAME, sBaseUrl, sUrl, sBrowserType);
        lCssSelector      += oLocatorsBenchmark.fillData(iMaxFillInput, LocatorsBenchmark.CSS_SELECTOR, sBaseUrl, sUrl, sBrowserType);
        lRelativeXpath    += oLocatorsBenchmark.fillData(iMaxFillInput, LocatorsBenchmark.RELATIVE_XPATH, sBaseUrl, sUrl, sBrowserType);
        lAbsoluteXpath    += oLocatorsBenchmark.fillData(iMaxFillInput, LocatorsBenchmark.ABSOLUTE_XPATH, sBaseUrl, sUrl, sBrowserType);
        lNameAsIdentifier += oLocatorsBenchmark.fillData(iMaxFillInput, LocatorsBenchmark.NAME_AS_IDENTIFIER, sBaseUrl, sUrl, sBrowserType);
        System.out.println("===================================\n");
      }
      /*************************
       * Calculate average time.
       *************************/
      System.out.println("SUMMARY: "+sBrowserType+ "["+iTry+" tries]");
      System.out.println("=========================");
      System.out.println( (new Formatter()).format("%27s %11s %-32s", "ID Avg. = ", (double)lId/(double)iTry+" ms", "  (id=idX)") );
      System.out.println( (new Formatter()).format("%27s %11s %-32s", "NAME Avg. = ", (double)lName/(double)iTry+" ms", "  (name=nameX)") );
      System.out.println( (new Formatter()).format("%27s %11s %-32s", "CSS_SELECTOR Avg. = ", (double)lCssSelector/(double)iTry+" ms", "  (css=input[name=\"nameX\"])") );
      System.out.println( (new Formatter()).format("%27s %11s %-32s", "RELATIVE_XPATH Avg. = ", (double)lRelativeXpath/(double)iTry+" ms", "  (xpath=//input[@name='nameX'])") );
      System.out.println( (new Formatter()).format("%27s %11s %-32s", "ABSOLUTE_XPATH Avg. = ", (double)lAbsoluteXpath/(double)iTry+" ms", "  (xpath=/html/body/input[X])") );
      System.out.println( (new Formatter()).format("%27s %11s %-32s", "NAME_AS_IDENTIFIER Avg. = ", (double)lNameAsIdentifier/(double)iTry+" ms", "  (identifier=nameX)") );
    }
  }
 
  /**
   * Implementation of benchmark class. 
   */
  public static int ID                = 0;
  public static int NAME              = 1;
  public static int RELATIVE_XPATH    = 2;
  public static int ABSOLUTE_XPATH    = 3;
  public static int NAME_AS_IDENTIFIER= 4; // Use the value of @name as identifier.
  public static int CSS_SELECTOR      = 5;
 
  private String[] m_aLocatorType = new String[]{ "ID", 
                          "NAME", 
                          "RELATIVE_XPATH",
                          "ABSOLUTE_XPATH", 
                          "NAME_AS_IDENTIFIER",
                          "CSS_SELECTOR", 
                          };
 
  private void generateData(final String sFilename, final int iMax)
  {
    try
    {
      BufferedWriter out = new BufferedWriter(new FileWriter(sFilename));
      out.write("<html><head><title>Selenium benchmark data</title></head><body>");
      for(int i=0; i<iMax; i++)
      {
        out.write("<input type=\"text\" id=\"id"+i+"\" name=\"name"+i+"\"/> "+i+"<br />");
      }
      out.write("</body></html>");
      out.close();
    }
    catch(IOException e) 
    {
      System.out.println(e.getMessage()+":\n"+e.getStackTrace());
    }   
  }
 
  private final long fillData(final int iMax, final int iLocatorType, final String sBaseUrl, final String sUrl, final String sBrowserType)
  {
    /*********************
     * Open test web page.
     *********************/
    final String sServerHost = "localhost";
    final int iServerPort = 4444;
    DefaultSelenium oDefaultSelenium = new DefaultSelenium(sServerHost, iServerPort, sBrowserType, sBaseUrl);
 
    oDefaultSelenium.start();
//oDefaultSelenium.useXpathLibrary("javascript-xpath");
    oDefaultSelenium.open(sUrl);
 
    /**************************************
     * Time time took to fill input fields.
     **************************************/
    Calendar oStart = Calendar.getInstance();
    for(int i=0; i<iMax; i++)
    {
      if(iLocatorType==ID)
      {
        oDefaultSelenium.type("id=id"+i, i+""); // ID
      }
      else if(iLocatorType==NAME)
      {
        oDefaultSelenium.type("name=name"+i, i+""); // NAME
      }
      else if(iLocatorType==RELATIVE_XPATH)
      {
        oDefaultSelenium.type("xpath=//input[@name='name"+i+"']", i+""); // RELATIVE_XPATH
      }
      else if(iLocatorType==ABSOLUTE_XPATH)
      {
        oDefaultSelenium.type("xpath=/html/body/input["+(i+1)+"]", i+""); // ABSOLUTE_XPATH
      }     
      else if(iLocatorType==NAME_AS_IDENTIFIER)
      {
        oDefaultSelenium.type("identifier=name"+i, i+""); // NAME_AS_IDENTIFIER
      }
      else if(iLocatorType==CSS_SELECTOR)
      {
        oDefaultSelenium.type("css=input[name=\"name"+i+"\"]", i+""); // CSS_SELECTOR
      }     
      else
      {
        System.out.println("Unknown Locator type: "+iLocatorType);
      }
    }
    Calendar oEnd = Calendar.getInstance();
 
    // Uncomment below to pause the execution of intructions so that you can see the results.
//    try{ Thread.sleep(10000); } catch(Exception ex){System.out.println(ex.getMessage());}
 
    oDefaultSelenium.stop();
 
    /************************
     * Calculate statistics. 
     ***********************/
    long lTotalRuntime = oEnd.getTimeInMillis() - oStart.getTimeInMillis();
    long lRuntime = lTotalRuntime;
 
    long lRuntimeHrs = lRuntime/(1000*3600);
    lRuntime = lRuntime - (lRuntimeHrs*1000*3600);// Runtime remaining.
    long lRuntimeMin = (lRuntime)/(1000*60);
    lRuntime = lRuntime - (lRuntimeMin*1000*60);  // Runtime remaining.
    long lRuntimeSec = lRuntime/(1000);
    lRuntime = lRuntime - (lRuntimeSec*1000);     // Runtime remaining.
 
    System.out.println(this.m_aLocatorType[iLocatorType]+" => Time Elapsed("+lTotalRuntime+" ms): "+lRuntimeHrs+" hr(s)  "+lRuntimeMin+" min(s)  "+lRuntimeSec+" sec(s)  "+lRuntime+" ms");
    return lTotalRuntime;
  }
 
}
AttachmentSize
HTML icon SeleniumData.html27.1 KB
File LocatorsBenchmark.java7.59 KB

Where to put Selenium.stop() within testing framework?

When using Selenium with a testing framework such as JUnit or TestNG, it is better to put selenium.stop() in the "closing method"(i.e. @After*) instead of in the test method itself. In this way, if tests failed, then the testing framework will be able to close the browser. Thus, you will save a lot of computer resources if your tests are opening and closing the browser thousands of times.

Code below show that TestNG will close the browser even the method failed.

/**
 * ShowCloseBrowser.java
 * Show that even though the test method fail, TestNG will close the browser.
 * @Author: Xuan Ngo
 */
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.testng.Assert.assertTrue;
 
import com.thoughtworks.selenium.DefaultSelenium;
 
@Test(sequential=true)
public class ShowCloseBrowser
{
  private DefaultSelenium selenium = null;
 
  @BeforeMethod
  public void runBeforeEachTestMethod()
  {
    final String sServerHost  = "localhost";
    final int iServerPort     = 4444;
    final String sBrowserType = "*iexplore";
    final String sBaseUrl     = "http://www.google.ca/";
 
    this.selenium = new DefaultSelenium(sServerHost, iServerPort, sBrowserType, sBaseUrl);
    this.selenium.start(); // Start selenium.
 
    this.selenium.open("http://www.google.ca/index.html"); // Open the main google webpage.
  }
 
  @AfterMethod
  public void runAfterEachTestMethod()
  {
    this.selenium.stop(); // Close browswer.
  }
 
  @Test(description="Show that TestNG will close the browser even the test fail.")
  public void myFailedTest()
  {
    assertTrue(false, "Explicitly fail this test.");
  }
}

Get the lastest developement version of Selenium

Softwares requirements

  • Subversion client
  • Maven

Get the lastest developement version of Selenium

  1. Get the latest code from SVN repository.
    svn export http://svn.openqa.org/svn/selenium-rc/trunk
     
  2. Go to the directory where pom.xml is located and build everything.
    cd trunk
    mvn install
     
  3. selenium-server-*-SNAPSHOT-standalone.jar is located at trunk\selenium-server\target\. selenium-java-client-driver-*-SNAPSHOT.jar is located at trunk\clients\java\target.