Automate web application UI testing with Selenium

This article was originally published in VSJ, which is now part of Developer Fusion.

Web-based applications have become an integrated part of every computer user’s life. We now use words such as “google” as freely as any common verb, signifying our dependence and preference to use the browser as our interaction tool of choice when accessing the Internet. There are lots of repetitious and tedious actions that one performs daily on a browser. It would be ideal to have access to a tool, native to a browser, to enable the automation of such common tasks.

On the flip side of the coin, if you are creating web applications, is the paramount importance that you test thoroughly before allowing user access. Such testing can require long hours of very expensive human resource to repeatedly exercise the application against a varied list of input conditions.

Selenium, a browser-based testing and automation framework, can solve both of these problems for software developers.

This article provides a hands-on introduction to Selenium from a .NET and Java developer’s perspective. You will discover Selenium’s components, its flexible architecture, how it works, and how to effectively use it for application development and testing activities.

The Selenium components

As a web application testing framework and toolkit, one of Selenium’s key strength lies in its rich support for a wide variety of browsers and platforms. All major versions of Firefox, Internet Explorer, Safari, Opera, and Mozilla are supported; together with the main Windows, Linux, and Mac OS platforms. Selenium also supports test creations in a variety of programming language including C#, Java, Python, Perl, PHP, and Ruby. The wide range of browser, platform, and programming language support enhances Selenium’s utility and enable you to tailor it for your specific testing requirements.

When you visit the Selenium website, you will discover that Selenium is not one single project/product, but is made up of multiple related, yet separate, components. Depending on your requirements, you can pick and choose from these components to create your Selenium based testing system.

  • Selenium Core is a test framework for web applications written completely in JavaScript and DHTML. Supporting multiple versions of the most popular browsers, it is designed to run within the browser, utilizing its scripting capabilities to simulate user input, to capture/compare expected output. As the name implies, this is the core component that others depends on. The framework includes a TestRunner written in JavaScript that can be used to run tests directly from a browser.
  • Selenium IDE is a Firefox add-on that provides an advanced test case creation and development facility for Selenium. It works only with Firefox only as it is written in JavaScript and Firefox Chrome (see VSJ article “Reveal your brilliance with Firefox 2 Chrome” January 2007 for more information on Chrome). You can use Selenium IDE to capture your interactions with a web application and turn them into test case code. It is capable of generating test case code in C#, Java, Python, Perl, PHP, Ruby, and Selenium’s own “native” HTML table based command language format.
  • Selenium Remote enables you to run Selenium tests across a network connection. The tests can be written in a variety of programming languages including C#, Java, Python, Perl, PHP and Ruby. This makes integration of language/platform specific test frameworks possible – you can use frameworks such as NUnit, JUnit, and TestNG with Selenium Remote. On the client-side, drivers are available for each of the supported languages for communications with the Selenium Remote server, which is written in Java.
  • Selenium Grid extends Selenium Remote to run tests simultaneously, in parallel, across multiple nodes in a “farm” of test machines. This dramatically increases total system throughput and can scale to run tens of thousands of tests in continuous integration systems. Selenium Grid can run on your own network of commodity PC/servers, or on the Amazon Elastic Compute Cloud (EC2) cloud computing service.

This article examines Selenium Core, IDE and Remote, showing how they work individually and how they work together collectively, and you will get some hands-on time with each technology. Selenium Grid is outside of the scope of this article; explore it further at selenium-grid.seleniumhq.org.

Operation of Selenium Core

Figure 1 depicts Selenium Core running test cases on a browser, accessing a web application running on a separate server (typically over a network or the Internet). The dashed line represents the browser loading of code, web pages, and scripts. The solid line represents runtime interaction between the browser and the server.

Figure 1
Figure 1: How Selenium Core works

The first thing to note in the figure is that Selenium Core, and the test cases, all reside on the application server. As the dashed lines indicate, they are loaded into the browser and executed in the browser during runtime. When test cases execute in Selenium Core, they interact with the application using commands that you have specified in the test cases, and confirm the expected output. Selenium Core, being in JavaScript and running in the browser, has complete access to the rich Document Object Model (DOM) exposed by modern browsers, and uses it to accomplish its tasks.

Test cases are stored on the server, and can be accessed with Selenium Core’s built-in TestRunner mini-application.

Standalone Selenium Core

Selenium Core is completely self-contained. That is: you can run tests against a web application using Selenium Core alone – you do not necessarily need the other components. There are some restrictions when using Selenium Core standalone, however. First, you can only use the built-in TestRunner to orchestrate your test cases – which can be rather limiting if you have a lot of tests to run or if they require complicated handling. Secondly, your test cases must be hand-crafted in Selenium’s “native” HTML table based command language (you will see an example of this language a little later in the hands-on section of this article). If you want to write your test cases in C#, Java, Python, PHP, Perl, or Ruby; or if you want to use a more sophisticated test management framework such as NUnti, JUnit, or TestNG, you will need Selenium Remote’s multi-language driver support. Thirdly, Selenium Core must load from the same server as the application being tested. This is necessary because of the security policy enforced by all modern browsers. JavaScript code, such as the Selenium Core, must originate from the same server (URL) source as the web application being tested. Most of the time, this is not a problem, because you own and have control over the server hosting the application yourself. However, where you do not have control of the server hosting the application, you’ll need to use Selenium Remote’s proxy capabilities to circumvent this problem (described in the Selenium Remote section).

Operation of Selenium IDE

The Selenium IDE is enables the crafting Selenium test cases and collections of test cases called test suites. As a Firefox add-on, it has read and write access to the local disk for storing test cases and suites that you create. (See Figure 2.)

Figure 2
Figure 2: How Selenium IDE works

Test cases can be coded using Selenium’s own HTML based command language, or you can take advantage of Selenium IDE’s ability to record (capture) actions as you work with the remote web applications. These actions are converted to the HTML based command language and can be saved as HTML files. Each sequence of actions can be named and saved separately, enabling you to use Selenium IDE as a macro player for frequently executed actions. By default, Selenium IDE generates code in the HTML based command language that Selenium Core can run directly. However, if you need to work in other programming languages, such as C# or Java, Selenium IDE can convert the commands to language specific API calls that are compatible with Selenium Remote.

It is not mandatory to use the Selenium IDE when creating Selenium tests – you can write the code from scratch using a text editor. However, exploiting Selenium IDE’s action capture and interactive code generation feature can save you substantial time and increase your productivity.

How Selenium Remote Works

Selenium Remote is easily the most complex of the three Selenium components.

In Figure 3, it is important to differentiate between the roles of the three machines. The Test Runner machine is where you can run your Selenium test cases. When using Selenium Remote Control, your test case can be written in any of the supported programming language, including C# or Java. On the Test Runner machine, for example, you can have NUnit driving Selenium tests written in C#. These tests access a language specific API that is provided by the Selenium Remote Control Client Driver. The Selenium Remote Control Client Driver converts the API calls into requests that are sent over the network to the Selenium Remote Control Server Component.

Figure 3
Figure 3: How Selenium Remote works

The second machine role is the Test Machine which is where the Selenium Remote Control Server Component runs. On the Test Machine, the Selenium Remote Control Server Component listen for network commands from the Client Driver. These commands are carried out by the Server Component by starting a Browser instance, loading Selenium Core into the browser, and then coordinating with Selenium Core. The Selenium Remote Control Server Component is written completely in Java. However, since you do not interact directly with the Server Component code, but only through a network connection, the test cases executed by the server can be written in any supported programming language.

Another very valuable service that the Selenium Remote Control Server Component performs on the Test Machine is request proxying. The proxy logic intercepts and examines the URL requested by the browser instance. When it matches a certain pattern, the proxy provides the response instead of passing it through the network. For example, it can be used to make Selenium Core appears as if it is residing on the Application Server machine. This is the mechanism that enables you to test applications running on servers that you don’t control. Due to security policies on modern browsers, the JavaScript code of the Selenium Core must come from the same server as the application that is being tested. By making the Selenium Core appear to be coming from the same server as the application, the browser is fooled into allowing Selenium Core to interact with the web application running on a different machine.

The last machine role in Figure 3 is the Application Server where the web application being tested is located. The big difference in this case compared to Figure 1 is the location of the Selenium Core code. Thanks to the proxy feature of the Selenium Remote Server Component, Selenium Core need not be located on the application server, allowing you to run tests against public Internet sites and other servers that are out of your control.

The above discussion mentions three distinct machine roles. Of course, all three machines roles can be running on the same physical machine if you’re just trying out Selenium and using loop-back networking connections.

In summary, you can think of the three machine roles as:

  1. Test runner where you run your C# or Java test cases with the .NET or Java Selenium Remote Control Driver Component installed
  2. Test machine where the browser used for testing is installed and the Selenium Remote Control Server Component is running
  3. Application server where the web application that you want to test is running

Hands-on testing with Selenium

First, you need a web application to test. The code distribution includes a VSJ Calculator application created using ASP.NET; a version created using JSP for Java developers is also included. This application performs basic addition, subtraction, multiplication, and division on the server; it also handles divide by zero gracefully. Figure 4 shows an instance of VSJ Calculator running in Internet Explorer.

Figure 4
Figure 4: Example application running in IE

Before proceeding, you need to install and make sure this application is running properly. If you are using Microsoft IIS, Place the vsjcalc.aspx file at the root directory of the default website. As an example, if you are on Windows XP Professional SP2 running IIS 5.1, this directory is by default:

c:\Inetpub\wwwroot

Of course, you should initially make sure the optional Internet Information Server Windows component is installed on your system.

For Java developers, you can install the JSP version instead. To run it, make sure you have Tomcat 6 installed and running. The test system used Tomcat 6.016 but any recent release of Tomcat 6 should work fine. Just copy the vsjcalc.war file to Tomcat’s webapps directory and then start the server.

Access the application and make sure it is running correctly. Use this URL for IIS deployment – see Figure 4:

http://<host of application>/vsjcalc.aspx

…and this for Tomcat deployment:

http://<host of application>:8080/
    vsjcalc/vsjcalc.jsp

You should try using both Firefox and Internet Explorer. This web application works with both browsers; and Selenium can be used to test it using either.

All the tests have been performed using Internet Explorer version 7.0.5730.11, and should work with most IE 6 and 7 versions. The version of Firefox used is 3.0.4.

Feel free to explore the ASP .NET source code to vsjcalc.aspx or the JSP source code of vsjcalc.war. We will not examine it here in order to maintain our focus on Selenium.

Testing with Selenium Core

Download the latest available version of Selenium Core. The version used in this article is version 0.8.3.

Create a directory called selcore at the root of your application server and unzip the core distribution under this directory. On IIS/Windows XP, the directory created would be:

c:\Inetpub\wwwroot\selcore.

On a Tomcat server, you should create the selcore directory under webapps\ROOT. In the selcore directory, unzip the corresponding vsjtests.zip file (IIS or Tomcat) from the code download. This should create a <website root>/selcore/vsjtests directory containing the test cases for the web application (they are HTML files).

With Selenium Core and the test cases installed, you can access its built-in TestRunner application. Try this for IIS deployment:

http://<host of selenium core>
    /selcore/core/TestRunner.html

…and this for Tomcat:

http://<host of selenium core>
    :8080/selcore/core/TestRunner.html

On your browser, you should make sure that you have allowed popups from the application server, and enabled cookies – some tests you run may require these settings.

In the top left corner of the TestRunner screen, enter the name of the test suite for our VSJ Calculator:

../vsjtests/VSJCalTests.html

This loads the VSJ Calculator test suite into the Selenium Core test runner. Figure 5, which shows the Firefox browser accessing a Tomcat 6 deployment of Selenium Core, shows the test suite loaded and the commands of the TestSubtract test case displayed.

Figure 5
Figure 5: Running TestSubtract with Selenium

In this test case, you can see the commands that will be executed in an HTML table (in the Current Test box). This is the “native” test case command language that Selenium Core understands. The table below describes each of the command lines in this test case.

Command Description
open /vsjcalc.aspx -In the browser, access the URL http://<current host>/vsjcalc.aspx
type x 4 In the field named x , enter the value 4
type y 3 In the field named y, enter the value 3
select operation label=subtract Using the <select> element named operation, choose “subtract” from all the choices
clickAndWait //input[@value=’Calculate’] Look for the button with value of ‘Calculate’, click it and wait for a response page
assertText //div 4 – 3 = 1 In the response page, look for the <div> element (the //div notation is an XPath expression); within the <div>, look for and confirm that it contains the text “4 – 3 = 1”
See the Selenium Core documentation for many more available commands.

The HTML “code” for this test case is shown in the following listing:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML
    Strict//EN"
    "http://www.w3.org/TR/xhtml1/
    DTD/xhtml1-strict.dtd">
<html
    xmlns="http://www.w3.org/1999/xhtml"
    xml:lang="en" lang="en">
    <head profile="http://selenium-ide.
    	openqa.org/profiles/test-case">
    <meta http-equiv="Content-Type"
    content="text/html; charset=UTF-8" />
    <link rel="selenium.base"
href="http://localhost:8080/vsjselenium/"
    	/>
    	<title>TestSubtract</title>
    </head>
    <body>
    	<table cellpadding="1"
    			cellspacing="1" border="1">
    		<thead>
    			<tr><td rowspan="1" colspan="3">
    					TestSubtract
    			</td></tr>
    		</thead>
    		<tbody>
    			<tr>
    				<td>open</td>
    				<td>/vsjcalc/vsjcalc.jsp</td>
    				<td></td>
    			</tr>
    			<tr>
    				<td>type</td>
    				<td>x</td>
    				<td>4</td>
    			</tr>
    			<tr>
    				<td>type</td>
    				<td>y</td>
    				<td>3</td>
    			</tr>
    			<tr>
    				<td>select</td>
    				<td>operation</td>
    				<td>label=subtract</td>
    			</tr>
    			<tr>
    				<td>clickAndWait</td>
    <td>//input[@value='Calculate']</td>
    				<td></td>
    			</tr>
    			<tr>
    				<td>assertText</td>
    				<td>//div</td>
    				<td>4 - 3 = 1</td>
    			</tr>
    		</tbody></table>
    </body>
</html>

There are six test cases covering addition, multiplication, subtraction, division, and two different variations of divide by zero. You should take a look at the other tests in this suite for some idea of how to write Selenium test cases. To run the entire suite using Selenium Core’s TestRunner, click on the left-most icon in the “Execute Tests” box in the “Control Panel” – see Figure 5. You will see Selenium Core start another browser window, load the VSJ Calculator application, and run through all the tests.

Creating Test Suites with Selenium IDE6

You need a running Firefox browser to get Selenium IDE installed. Selenium IDE installs conveniently as an add-on and Firefox will restart after the installation. Firefox 3.0.4 is used for this article.

Once installed, you can go to the Firefox menu Tools->Selenium IDE to activate the IDE. The IDE runs in its own popup window. Figure 6 shows Selenium IDE running.

Figure 6
Figure 6: Selenium IDE in operation

By default, Selenium IDE starts out with recording active. This is indicated by a red button on the top left corner of the IDE. When recording is active, any interactions with the Firefox browser are recorded as Selenium test commands. For example, you can:

  1. Type http://www.google.com/ into the Firefox browser
  2. Enter VSJ into the Google search screen
  3. Click the “Google Search” button

Now take a look at the Selenium IDE, you will see the command recorded in the HTML table based command language (seen earlier with Selenium Core). Figure 6 shows the commands captured by Selenium IDE. If you click on the Source tab of the Selenium IDE, you can see the HTML source code of the commands that you’ve just captured.

To play back the commands, first click the red button to stop recording, then press the green triangular play button. You will see Selenium IDE replaying each of the captured commands on the Firefox browser window. The test case can then be saved to the local disk. Multiple test cases can be combined into a test suite and saved on the local disk. Just like a fully fledged IDE, Selenium IDE can provide developer with help on Selenium commands when creating test cases – just click the Reference tab on the bottom half of the IDE window (see Figure 6 showing the help for the clickAndWait command).

The HTML based command language can also be transcoded into C#, Java, Perl, PHP, Python, or Ruby – just change the menu Options–>Format settings. The generated test case code can be helpful if you write your test using one of these programming languages, and use Selenium Remote Control for testing.

Running tests in Selenium IDE

To try a suite of tests, unzip the vsjtests.zip file from the code download, and load the VSJCalTests.html file (a test suite) into Selenium IDE. Be careful to use the correct vsjtests.zip, there is one for IIS hosted application and another for Tomcat hosted application.

When you load the VSJCalTests.html test suite into Selenium IDE, you will see all six tests loaded as a suite. You can run any individual test or the entire suite together using Selenium IDE. Just double click on the name of the test case.

Notice that when running tests using the Selenium IDE, you do not need to have Selenium Core installed on the application server. Selenium IDE can control the behaviour of the Firefox browser directly as an Add On.

A tip: when working with Selenium IDE, develop a habit of saving your test cases (and suites) frequently as HTML files (with the proper .html extension). This ensures that your work is preserved, and can be restored quickly, should something unexpected happens during your interactions.

C# and Java based testing with Selenium Remote Control

To try out Selenium Remote Control, you will need to setup three machine roles:

  1. Test runner machine where the test framework (NUnit or JUnit) is installed, and the C# or Java test cases are stored, and where the C# or Java Selenium Remote Control driver is located
  2. Test machine where the browser (Internet Explorer or Firefox) you’ll be using resides and Selenium Remote Control server has started
  3. Application server where vsjcalc.aspx or vsjcalc.war is running

See Figure 3 for a refresher of what occurs between the three machine roles. You can use one single machine to simulate all three roles by using localhost loopback networking.

On the application server, make sure you have vsjcalc running (on IIS or Tomcat) and ready. Test it manually with a browser.

On the test machine, download Selenium Remote Control. You need a distribution that is dated Nov 2008 or later, if you do not find a release or beta that is recently dated, use the daily snapshot. The older 1.0 Beta 1 release has a Firefox shutdown bug that can prevent automated tests from running on some Windows systems.

When you unzip the Selenium Remote Control distribution, you should have the following directories:

selenium-dotnet-client-driver-1.0
selenium-java-client-driver-1.0
selenium-perl-client-driver-1.0
selenium-php-client-driver-1.0
selenium-python-client-driver-1.0
selenium-ruby-client-driver-1.0
selenium-server-1.0

The directory names may be slightly different depending on the release and/or snapshot date.

You’ll need to have a version of Java SE installed and running before running the server. SUN’s Java SE 1.6.0_10 was used for this article.

To start the Selenium Remote Control server, change directory into selenium-server-1.0, and run:

java -jar selenium-server.jar

This starts the Selenium Remote Control server listening for commands (on port 4444) and ready to proxy requests.

Now on the Test Runner machine, download and unzip the Selenium Remote Control distribution.

For C# developers, you can unarchive the csharptests.zip file from the download into the selenium-dotnet-client-driver-1.0 directory.

For Java developers, unzip the javatests.zip file from the download into the selenium-java-client-driver-1.0 directory.

NUnit driven testing with Selenium Remote Control

The C# based tests are contained in the VSJTests.cs file. It is written to work with the open source NUnit test framework. VSJTests.cs is shown in this listing:

using System;
using System.Text;
using System.Threading;
using NUnit.Framework;
using Selenium;
namespace VSJCalTests
{
    [TestFixture]
    public class VSJTests
    {
    	private ISelenium selenium;
    	private StringBuilder
    		verificationErrors;

    	[SetUp]
    	public void SetupTest()
    	{
    		selenium = new DefaultSelenium(
    			"localhost", 4444,
    			"*chrome",
    			"http://192.168.23.66/");
    		selenium.Start();
    		verificationErrors =
    			new StringBuilder();
    	}

    	[TearDown]
    	public void TeardownTest()
    	{
    		try
    		{
    			selenium.Stop();
    		}
    		catch (Exception)
    		{
    			// Ignore errors if unable to
    			// close the browser
    		}
    		Assert.AreEqual("",
    			verificationErrors.ToString());
    	}

    	[Test]
    	public void TestAdd()
    	{
    		selenium.Open("/vsjcalc.aspx");
    		selenium.Type("x", "4");
    		selenium.Type("y", "3");
    		selenium.Select("operation",
    			"label=add");
    		selenium.Click(
    			"//input[@value='Calculate']");
    selenium.WaitForPageToLoad("30000");
    		Assert.AreEqual("4 + 3 = 7",
    			selenium.GetText("//div"));
    	}

    	[Test]
    	public void TestSubtract()
    	{
    		selenium.Open("/vsjcalc.aspx");
    		selenium.Type("x", "4");
    		selenium.Type("y", "3");
    		selenium.Select("operation",
    			"label=subtract");
    		selenium.Click(
    			"//input[@value='Calculate']");
    selenium.WaitForPageToLoad("30000");
    		Assert.AreEqual("4 - 3 = 1",
    			selenium.GetText("//div"));
    	}

    	[Test]
    	public void TestMultiply()
    	{
    		selenium.Open("/vsjcalc.aspx");
    		selenium.Type("x", "4");
    		selenium.Type("y", "3");
    		selenium.Select("operation",
    			"label=multiply");
    		selenium.Click(
    			"//input[@value='Calculate']");
    selenium.WaitForPageToLoad("30000");
    		Assert.AreEqual("4 * 3 = 12",
    			selenium.GetText("//div"));
    	}

    	[Test]
    	public void TestDivide()
    	{
    		selenium.Open("/vsjcalc.aspx");
    		selenium.Type("x", "4");
    		selenium.Type("y", "3");
    		selenium.Select("operation",
    			"label=divide");
    		selenium.Click(
    			"//input[@value='Calculate']");
    selenium.WaitForPageToLoad("30000");
    		Assert.AreEqual("4 / 3 = 1.33",
    			selenium.GetText("//div"));
    	}

    	[Test]
    	public void TestDivideByZero()
    	{
    		selenium.Open("/vsjcalc.aspx");
    		selenium.Type("x", "4");
    		selenium.Type("y", "0");
    		selenium.Select("operation",
    			"label=divide");
    		selenium.Click(
    			"//input[@value='Calculate']");
    selenium.WaitForPageToLoad("30000");
    		Assert.AreEqual(
    			"Cannot divide by zero.",
    			selenium.GetText("//div"));
    	}

    	[Test]
    	public void TestDivideByZero2()
    	{
    		selenium.Open("/vsjcalc.aspx");
    		selenium.Type("x", "4");
    		selenium.Type("y", "0.0");
    		selenium.Select("operation",
    			"label=divide");
    		selenium.Click(
    			"//input[@value='Calculate']");
    selenium.WaitForPageToLoad("30000");
    		Assert.AreEqual(
    			"Cannot divide by zero.",
    			selenium.GetText("//div"));
    	}
    }
}

Note the highlighted code – you must change localhost to match the IP address of your Test Machine (where the Selenium Remote Control Server Component is running) and the IP address 192.168.23.66 to match your Application Server’s IP address. This code assumes that you are hosting VSJ Calculator via IIS and using Firefox for testing on the Test machine.

Compare this code to the HTML based Selenium native test cases, and you should see a one-to-one correspondence. Selenium Remote Control driver provides a language specific API to drive the Selenium test engine.

Tip: when creating your own test cases, if you are ever confused as to which API is best to use for a specific scenario, remember that you can use Selenium IDE to capture your interactions with the application and then generate the C# API calls required to run them.

Before you can run this test, you will need to compile it and have NUnit installed and running.

Assuming you have Microsoft .NET Framework 2 installed and running. You can compile the VSJTests.cs file using the command (all on one line):

csc /nologo /t:library
    /r:nunit.framework.dll
    /r:ThoughtWorks.Selenium.Core.dll
    VSJTests.cs

This output of this compilation is the VSJTests.dll file. This file is a tests suite library that can be used to run the test cases. You can also use the compile.bat batch file to perform the compilation.

To run the test cases, assuming you have NUnit installed and working. Either start the NUnit GUI Test Runner and load the VSJTests.dll suite, or right click on VSJTests.dll and select “Run Tests”. Once NUnit has loaded the suite, click the “Run” button in the GUI Test Runner to start the tests. Figure 7 shows NUnit running the tests.

Figure 7
Figure 7: NUnit running the tests

Recall that the APIs provided actually translate to networked commands being sent to the Test Machine, via Selenium Remote Control. On the Test Machine where the Selenium Remote Control Server Component is running, you should see Firefox start up and access the VSJ Calculator application.

The VSJTests.cs code has been tested with NUnit 2.4.8.

JUnit driven testing with Selenium Remote Control

The Java based tests are contained in the VSJTests.java file. It is written to work with the open source JUnit test framework and has been tested with JUnit 3.8.2. The VSJTests.java source code is shown in the following listing:

import com.thoughtworks.selenium.*;
import junit.framework.*;
public class VSJCalTest
    extends SeleneseTestCase {
    private Selenium selenium;

    public void setUp() throws Exception {
    	selenium = new DefaultSelenium(
    	"localhost",4444, "*firefox",
    	"http://192.168.23.66");
    	selenium.start();
    }

    public void tearDown() {
    	selenium.stop();
    }

    public void testAdd() throws Exception {
    	selenium.open("/vsjcalc.aspx");
    	selenium.type("x", "4");
    	selenium.type("y", "3");
    	selenium.select("operation",
    		"label=add");
    	selenium.click(
    		"//input[@value='Calculate']");
    selenium.waitForPageToLoad("30000");
    	assertEquals("4 + 3 = 7",
    		selenium.getText("//div"));
    }

    public void testSubtract()
    	throws Exception {
    	selenium.open("/vsjcalc.aspx");
    	selenium.type("x", "4");
    	selenium.type("y", "3");
    	selenium.select("operation",
    		"label=subtract");
    	selenium.click(
    		"//input[@value='Calculate']");
    selenium.waitForPageToLoad("30000");
    	assertEquals("4 - 3 = 1",
    		selenium.getText("//div"));
    }

    public void testMultiply()
    	throws Exception {
    	selenium.open("/vsjcalc.aspx");
    	selenium.type("x", "4");
    	selenium.type("y", "3");
    	selenium.select("operation",
    		"label=multiply");
    	selenium.click(
    		"//input[@value='Calculate']");
    selenium.waitForPageToLoad("30000");
    	assertEquals("4 * 3 = 12",
    		selenium.getText("//div"));
    }

    public void testDivide()
    	throws Exception {
    	selenium.open("/vsjcalc.aspx");
    	selenium.type("x", "4");
    	selenium.type("y", "3");
    	selenium.select("operation",
    		"label=divide");
    	selenium.click(
    		"//input[@value='Calculate']");
    selenium.waitForPageToLoad("30000");
    	assertEquals("4 / 3 = 1.33",
    		selenium.getText("//div"));
    }

    public void testDivideByZero()
    	throws Exception {
    	selenium.open("/vsjcalc.aspx");
    	selenium.type("x", "4");
    	selenium.type("y", "0");
    	selenium.select("operation",
    		"label=divide");
    	selenium.click(
    		"//input[@value='Calculate']");
    selenium.waitForPageToLoad("30000");
    	assertEquals(
    		"Cannot divide by zero.",
    		selenium.getText("//div"));
    }

    public void testDivideByZero2()
    	throws Exception {
    	selenium.open("/vsjcalc.aspx");
    	selenium.type("x", "4");
    	selenium.type("y", "0.0");
    	selenium.select("operation",
    		"label=divide");
    	selenium.click(
    		"//input[@value='Calculate']");
    selenium.waitForPageToLoad("30000");
    	assertEquals(
    		"Cannot divide by zero.",
    		selenium.getText("//div"));
    }
}

Note the highlighted code – you must change localhost to match the IP address of your Test Machine (where the Selenium Remote Control Server Component is running) and the IP address 192.168.23.66 to match your Application Server’s IP address. This code assumes that you are hosting VSJ Calculator on IIS and using Firefox for testing on the Test Machine.

If you compare this code to the HTML based Selenium native test cases, you should see a one-to-one correspondence. Notice how the Java APIs replace the HTML table commands.

Tip: Selenium IDE can be used to discover the APIs that can be used to create your JUnit test cases.

Assuming you have JUnit 3.8.2 installed into c:\junit3.8.2 directory, you can compile the VSJCalTest.java file using the command (all on one line):

javac -classpath
    c:\junit3.8.2\junit.jar;selenium-java-
    client-driver.jar VSJCalTest.java

You need to replace the classpath to JUnit with your own JUnit installation path.

This compilation will create the VSJCalTest.class file. This file is a tests suite that can be used to run the test cases. You can also use the compile.bat batch file to perform the compilation.

To run the test cases, assuming again that JUnit is installed into c:\junit3.8.2, use the command (on one line):

java -classpath
    c:\junit3.8.2\junit.jar;selenium-java-
    client-driver.jar;.
    junit.swingui.TestRunner VSJCalTest

Figure 8
Figure 8: JUnit running the VSJ Calculator tests

You can also edit and use the run.bat file to start the tests. This will cause the JUnit Swing GUI test runner to load and run the tests. Figure 8 shows JUnit running the VSJ Calculator tests.

On the Test Machine, you should see Firefox start up and run the VSJ Calculator application.

Conclusions

Selenium IDEs allows you to create test cases simply by capturing interactions with web applications. Selenium Remote Control can work with popular programming languages such as C# and Java, as well as popular testing framework such as NUnit and JUnit. Selenium Core supports all popular browsers including Firefox, Internet Explorer, Safari, Mozilla, and Opera. Selenium Remote Control (and Selenium Grid) features a highly scalable architecture that can expand to thousands of simultaneously testing machines. Taken together, Selenium is a formidable toolset ready for the complex and heterogeneous challenges of today’s real-world web application testing.

You might also like...

Comments

About the author

Sing Li United States

Sing Li has been writing software, and writing about software for twenty plus years. His specialities include scalable distributed computing systems and peer-to-peer technologies. He now spends ...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“PHP is a minor evil perpetrated and created by incompetent amateurs, whereas Perl is a great and insidious evil perpetrated by skilled but perverted professionals.” - Jon Ribbens