Testing native Mobile Apps with TestComplete and Appium – An Alternative

[Note] This post was written well before SmartBear released TestComplete 10 with support for testing iOS and Android mobile apps. Please visit the SmartBear TestComplete product page for more details. This post is no longer valid and kept here as a reference.

My day job needs me to work on TestComplete a popular commercial testing tool from SmartBear Software. We do a lot of serious testing using TestComplete for our Desktop applications.

Recently I saw discussions on TestComplete User Forums about possibility of testing mobile apps using TestComplete.  While TestComplete supports testing on wide range of technologies and application platforms including Web and Desktop applications developed on Windows, .NET, WPF, Delphi, C++, Java and so on. However while writing this post it does not have in-built mobile testing capabilities. SmartBear is working on adding mobile testing features which are in beta phase. There are third party tool/plug-in(s) available which use Image Recognition based approach to test the applications. But there is no native support to test iOS or Android Apps.

With these thoughts in my mind, I started to explore if I could mix Appium with TestComplete which will allow testing mobile Apps without leaving the TestComplete environment? With couple hours of hacking, here are the results!

About Appium

Appium is an open source test automation framework for automating native and hybrid mobile apps.
It drives iOS and Android Apps using the WebDriver JSON wire protocol. Appium tests are built on Selenium WebDriver API.  The WebDriver API is used for driving user actions in Browsers, but now it can be used to drive the user interaction on native and hybrid mobile Apps. WebDriver API provides various language bindings which allow you to use them with your choice of programming language and platform, very cool!

How does this works?

TestComplete is a versatile tool and provides supports for more than dozen technologies and extensibility features. TestComplete provides a .NET Bridge which allows access to individual objects of .NET assemblies, their internal properties and methods. This is done by a special dotNET object that provides access to .NET assemblies, types and type members. This feature is available as part of .NET Classes Support plug-in in TestComplete.

Since Appium is driven by WebDriver API, we can connect the WebDriver .NET APIs with TestComplete using the .NET bridge and drive the mobile Apps using Appium. Following diagram provides an overview of this interaction

How to do it?

Setting up the WebDriver .NET API with TestComplete is relatively easy task. Following section describe the detailed steps for driving Appium through TestComplete for testing a sample iOS native App.

Step 1 – Download the WebDriver .NET API Binaries

Download the latest binaries from http://docs.seleniumhq.org/download/. You need to click on Download link in front of C# option in Selenium Client & WebDriver Language Bindings section.

Step 2 – Add WebDriver assemblies to TestComplete CLR Bridge

In next step make the WebDriver assemblies available to TestComplete with following steps. These assemblies will be added to the list in the project’s CLR Bridge settings group. This group contains the list of .NET assemblies whose functions will be available to your scripts through the dotNET object:

  1. Go to TestComplete Project Setting by selecting Current Project Settings from Tools Menu
  2. Select CLR Bridge option on left side of Project Properties Pane
  3. Click Browse Files button to select the WebDriver files. This will display Select Assembly dialog box
  4. On Select Assembly dialog navigate to the net40 folder in WebDriver .NET API files downloaded in Step 1 and select the WebDriver.dll and WebDriver.Support.dll files
  5. Also make sure System.dll is added to CLR Bridge. If it’s not added already, you can add this assembly by Browser GAC button. You will see screen similar to following screen shot after you add all the assemblies to the CLR Bridge
TestComplete CLR Bridge
TestComplete CLR Bridge

This will add WebDriver API to the TestComplete project and provide access to the internal classes and functions using the dotNET object. Assemblies that are added to the CLR Bridge become available in scripts as child objects of the dotNET object. Types defined in these assemblies are available as child of dotNET object. All available assemblies, types, and type members are displayed in the Code Completion window of TestComplete. For more information on dotNET object refer Calling .NET Routines via dotNET Object section in TestComplete Help documentation (also available at http://support.smartbear.com/viewarticle/28697/)

Step 3 – Setting up Appium

Before we start testing iOS or Android apps, we need to setup Appium in a local environment. If you wish to run tests for iOS, then you need to setup Appium on a Mac OSX machine. For testing Android applications you can setup environment on a Windows or Linux machine. Setting up Appium is fairly easy with new Appium App for Mac OSX.

In this example we will test a sample BMI Calculator application for iOS. This is a pretty simple App with bunch of UI elements on a single view. You can get the App source from https://github.com/upgundecha/BmiCalculator.

Let’s setup Appium on a Mac and TestComplete on a Windows machine

  1. On Mac machine download and install the Appium from http://appium.io
  2. Before we launch Appium, download the sample App from https://github.com/upgundecha/BmiCalculator/blob/master/Sample%20App/BmiCalculator.zip,
  3. Unzip BmiCalculator.zip file to get the BmiCalculator.app file
  4. Next, launch Appium on Mac. Select the App Path checkbox and choose the location of the App. Click on Launch button, Appium will launch the application in iOS Simulator as shown in below screenshot, now it’s ready for testing the App
Appium.app running on Mac
Appium.app running on Mac

Step 4 – Writing a test

TestComplete offers multiple language options to write your tests. You can write tests in JavaScript, VBScript, Delphi or C++/C# scripting languages. This example uses JavaScript.

Our test need to tell Appium about what platform is needed for executing the tests. This is done by creating an instance of DesiredCapabilities class of WebDriver API and setting up configuration information in key/value  pair.


//Set up the capabilities to run test on iOS application on local Appium server
Capabilities.setCapability(CapabilityType.BrowserName, "iOS");
Capabilities.setCapability(CapabilityType.Version, "6.1");
Capabilities.setCapability(CapabilityType.Platform, "Mac");

Create an instance of  RemoteWebDriver instance and point it to http://mymacmachine:4723/wd/hub in the test by using Uri class from .NET System namespace and desired capabilities defined earlier. Here mymacmachine could be different in your environment. You can specify Hostname or IP of the Mac machine where Appium is running.


//Set up the RemoteWebDriver
var uri = dotNET.System.Uri.zctor("http://mymacmachine:4723/wd/hub");
var driver = dotNET.OpenQA_Selenium_Remote.RemoteWebDriver.zctor_3(uri,Capabilities);

Here is complete script which tests the BMI calculator functionality (also available as a Gist @ https://gist.github.com/upgundecha/5894126)

function BmiCalculatorTest()
{
  try
  {
    	//Create an instance of DesirecCapabilities, CapabilityType and By Class using CLR Bridge & dotNET Object
    	var Capabilities = dotNET.OpenQA_Selenium_Remote.DesiredCapabilities.zctor();
    	var CapabilityType = dotNET.OpenQA_Selenium_Remote.CapabilityType;
    	var By = dotNET.OpenQA_Selenium.By;

    	//Set up the capabilities to run test on iOS application on local Appium server
    	Capabilities.setCapability(CapabilityType.BrowserName, "iOS");
    	Capabilities.setCapability(CapabilityType.Version, "6.1");
    	Capabilities.setCapability(CapabilityType.Platform, "Mac");

    	//Set up the RemoteWebDriver
    	var uri = dotNET.System.Uri.zctor("http://mymacmachine:4723/wd/hub");

    	var driver = dotNET.OpenQA_Selenium_Remote.RemoteWebDriver.zctor_3(uri,Capabilities);

    	//Get the Hight text field and enter value
    	var HeightField = driver.FindElement(By.Name("Height"));
    	HeightField.SendKeys("181");

    	//Get the Weight text field and enter value
    	var WeightField = driver.FindElement(By.Name("Weight"));
    	WeightField.SendKeys("80");

    	//Get the Calculate button and tap/click on it
    	var CalculateButton = driver.FindElement(By.Name("Calculate"));

    	CalculateButton.Click();

    	//Get the Bmi lables
    	var BmiLabel = driver.FindElement(By.Name("bmi"));
    	var BmiCategoryLabel = driver.FindElement(By.Name("category"));

    	//Check labels for expected values
    	if(aqObject.CompareProperty(BmiLabel.Text, cmpEqual, "24.42")) {
      	  Log.Checkpoint ("Calculated BMI is correct!");
    	}
    	else {
      	  Log.Error( "Calculated BMI does not match expected value");
    	}

    	if(aqObject.CompareProperty(BmiCategoryLabel.Text, cmpEqual, "Normal")) {
      	  Log.Checkpoint( "BMI Category is correct!");
    	}
    	else {
      	  Log.Error( "BMI Category does not match with expected value");
    	}
    	driver.Quit();
  }
  catch(err){
    Log.Error(err.Message);
  }
}

If you prefer TestComplete with VBScript, you can get the VBScript version @ https://gist.github.com/upgundecha/5894141

How this works?

When this test is executed, TestComplete calls the WebDriver API and connects to the Appium server using the RemoteWebDriver. Then it locates the UI elements using FindElement() method of WebDriver API. Test can locate the elements using various locator strategies provided by the By class of WebDriver API. In following example, test is locating Height text field from Bmi Calculator App using its name property. It then enters the specified text using SendKeys() method


//Get the Hight text field and enter value
var HeightField = driver.FindElement(By.Name("Height"));
HeightField.SendKeys("181");

This is pretty much similar to how TestComplete works with UI objects while testing Web or Desktop applications. After inputting the data, TestComplete verifies the expected outcome using its inbuilt verification methods. At the end of execution TestComplete generate a result log as shown in following screenshot

Test Results
Test Results

Running test with Sauce Labs

You may not always get a dedicated hardware to test these Apps. Sauce labs, the company behind Appium, provides you an ability to run Appium tests in a virtual environment without needing you to setup everything from scratch. This also saves you costs for setting up the infrastructure on your own.

So let’s setup and run this test with Sauce Labs. You need a free Sauce Labs account to begin with. Register for a free account on Sauce Labs and get the user name and access key. Sauce Labs provides all the needed hardware and software infrastructure to run your tests in the cloud.

For running tests in Sauce Labs environment, you need to upload your App to Sauce Labs temporary storage using Temporary Storage REST API. You can get the App compiled and built by developers and upload through curl command line utility (Windows users can get curl from http://curl.haxx.se/download.html)


curl -u <sauce_user_name>:<sauce_access_key> -X POST "http://saucelabs.com/rest/v1/storage/$SAUCE_USERNAME/my_ios_app.zip?overwrite=true" -H "Content-Type: application/octet-stream" --data-binary @my_ios_app.zip

We need to modify our test a bit to run on Sauce Labs. Apart from changing the Capabilities and RemoteWebDriver Uri, we need to pass Sauce Labs user name and access key. You can save these into TestComplete project variables. With following changes to earlier test, we can now run tests with Sauce Labs:


var USER_NAME = Project.Variables.SAUCE_USER_NAME
var ACCESS_KEY = Project.Variables.SAUCE_ACCESS_KEY

//Set up the capabilities to run test on iOS application on Sauce Labs
Capabilities.SetCapability(CapabilityType.BrowserName, "iOS 6.0");
Capabilities.SetCapability(CapabilityType.Platform, "Mac 10.8");
Capabilities.SetCapability("device", "iPhone Simulator");
Capabilities.SetCapability("app", "sauce-storage:my_ios_app.zip");
Capabilities.SetCapability("username",USER_NAME);
Capabilities.SetCapability("accessKey",ACCESS_KEY);

//Set up the RemoteWebDriver
var uri = dotNET.System.Uri.zctor("http://" + USER_NAME + ":" + ACCESS_KEY +  "@ondemand.saucelabs.com:80/wd/hub");
var driver = dotNET.OpenQA_Selenium_Remote.RemoteWebDriver.zctor_3(uri,Capabilities);

When you run the test you can login to your Sauce Labs account and see the progress in a Browser window. Based on desired capabilities, Appium provisions an instance of Mac in Sauce Labs cloud and drives the App.

Test Running on Sauce
Test Running on Sauce

You can also view test run in Sauce Labs dashboard with details of each step along with screenshot and video of entire run.

Sauce Dashboard
Sauce Dashboard

Summary

Appium bring exciting possibilities to TestComplete users for testing mobile applications in a platform independent way. These tests can be executed in a local environment or in the cloud or real devices in very a short time, with minimal efforts and costs. This brings more test coverage and faster feedback.

Four Picks #4

After a long pause I am restarting the “Four Picks” series back again and hope you find it useful. Here is 4th edition of “Four Picks”

  1. Josh Glade has written an excellent article Five Sins of Mobile Testing on Stickyminds. Josh has given some very important tips for building an effective mobile testing strategy and avoid some common mistakes. His point on testing mobile apps on Emulator Software is valid, however emulators also provide first line of defence before apps are tesed on real devices. If you’re interested in learning more about mobile testing, I also recommend reading Jonathan Kohl’s book Tap into Mobile Application Testing I’m currently reading this book. It is packed with some real practical advice on testing mobile apps, I’ll post a review soon.
  2. Testability and Cost of Change I found this post while watching a video lesson. A well researched post with examples from Google. It provides very useful tips on testability and associated costs. There is an interesting example on cost savings with a bug found during TDD (again a solid reason to adopt TDD)
  3. From One Expert to Another: Dale Emery  Dale Emery talks about his recent talk on Test Automation Zombie Apocalypse I loved this presentation, though I do not agree to all points. This provides great stuff to reflect on your test automation efforts and assess the good and bad things. I also recommend reading Tales of Test Automation Gone Wrong by Elisabeth Hendrickson, in fact we built a assessment out of this presentation to check health of our test automation projects.
  4. Mindmaps! Here is a beautiful mind map on testing tools I found on Twitter

[tweet https://twitter.com/BugFinders/status/353179395822854145 ]

 

[Tutorial] Creating a Selenium IDE extension for Web Table commands

Selenium IDE is a great tool to record and replay simple tests within the Firefox browser. It provides all the commands that are supported by Selenium out of the box. However, we might need to build custom commands that are not part of Selenium. Selenium IDE provides a way to implement custom commands in three-column format by building extensions in the JavaScript language. These are stored in separate .js files.

Selenium IDE does not have built-in commands to work with web tables and perform verification on tables as needed in tests. This post explains how to implement custom commands to test Web Tables using Selenium IDE.

Setup

Create a user-extensions.js file and save it to a location where Selenium IDE can find it easily

Adding custom commands

To create an extension, we need to use the selenium.prototype object and follow a particular pattern for naming the functions. As we are creating an extension to verify the table properties and contents, we need to prefix assert to the function names.

Create a command to verify the number of columns in a table. Copy the following function to the user-extensions.js file:

Selenium.prototype.assertTableCols = function(locator, value) {
  var table = this.browserbot.findElement(locator);
  Assert.matches(value, table.rows[0].cells.length.toString());
}

To verify the number of rows, create the following function in the user-extensions.js file:

Selenium.prototype.assertTableRows = function(locator, value) {
  var table = this.browserbot.findElement(locator);
  Assert.matches(value, table.rows.length.toString());
}

Finally, to verify data in a specific cell of a table, create the following function in the user-extensions.js file:

Selenium.prototype.assertTableCellData = function(locator, value) {
	var args = new Array();
	args = value.split("|");
	var rowIdx = parseInt(args[0]) - 1
	var colIdx = parseInt(args[1]) - 1
	var table = this.browserbot.findElement(locator);
	if(null != table.rows[rowIdx].cells[colIdx].childNodes[0].text)
		Assert.matches(args[2], table.rows[rowIdx].cells[colIdx].childNodes[0].text);
}

Adding User Extensions to Selenium IDE Options

Now let’s start using this user extension with Selenium IDE by adding to the Selenium IDE Options. Click on the Options Menu and then click on Options Submenu. This will launch the Selenium IDE Options Dialog box as shown in the following screenshot:

Selenium IDE Options dialog box
Selenium IDE Options dialog box

Select the Path for user-extensions.js file by clicking the Browse… button in front of Selenium Core extensions (user-extenions.js). Restart the Selenium IDE. You can see the newly added commands in Selenium IDE

New commands in Selenium IDE
New commands in Selenium IDE

Extending Selenium IDE is pretty simple. We can add new commands by adding functions to the Selenium object prototype, and the PageBot object prototype. On startup, Selenium IDE will automatically look through functions in user-extensions.js on these prototypes, using name patterns to recognize which ones are actions, assertions, and locators.

Selenium IDE commands are restricted to a three-column format. However, some commands might need more information to execute the command. For example, we created an extension for verifying the Cell data. This command needs the row, column, and expected value. We can specify these parameters in value argument by separating parameter values using a pipe character “|”. Inside the function, we can then split this string using “|” and pass the values to appropriate variables.

Sample Test

Here is a sample test which navigates to a Shopping Cart page and performs verification on table displayed on the page:

Sample test with new Selenium IDE command
Sample test with new Selenium IDE command

 

iOS Automation with Appium & Selenium

Note: This post is not up to date with latest release of Appium. An update coming soon…

Yesterday I saw a tweet on Appium release from Sauce Labs and immediately started exploring it. This post summarizes my initial experience with Appium.

Appium (http://appium.io/) is an open source tool/framework for automating iOS Native and Hybrid Apps. It uses the WebDriver JSON wire protocol to drive iOS apps.

Appium server is written in Node.js and talks to iOS using UIAutomation via Instruments. You can use the Selenium WebDriver API for writing tests which talk to Appium via JSON wire protocol for running the Selenium commands. This also gives you advantage of writing tests in your language of preference.

Installation

I found installing Appium quite easy on a local machine. You need Node.js installed before using Appium.

1. Install Node.js from http://nodejs.org/

2. Install WebDriver package for Node.js with the following command

sudo npm install wd

3. Install Appium with the following command

sudo npm install appium -g

4. Start the Appium server with the following command

appium &

Appium server will start at http://localhost:4723

Implementing test using Selenium WebDriver

I am using a sample BMI Calculator App developed with native iOS SDK for this example

Bmi Calculator App
Bmi Calculator App

Build the app using xcodebuild command (In this example the BmiCalc app)

xcodebuild -sdk iphonesimulator6.1

I am using Maven to setup a Java project for this test and here is pom.xml with the following dependencies added. For this example I have used IntelliJ IDEA. For more information on using Maven for Selenium script development refer bonus Chapter Integration with other Tools from my Selenium Testing Tools Cookbook

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.bmicalc.test</groupId>
    <artifactId>bmi-ios-test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>LATEST</version>
        <scope>test</scope>
    </dependency>
    </dependencies>
</project>

And here is BmiCalcTest class

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;

import java.io.File;
import java.net.URL;
import java.util.List;

import static org.junit.Assert.assertEquals;

public class BmiCalcTest {

    private WebDriver driver;

    @Before
    public void setUp() throws Exception {

        //Appium needs the path of app build
        //Set up the desired capabilities and pass the iOS SDK version and app path to Appium
        File app = new File("/Users/upgundecha/Desktop/AppExamples/BmiCalculator/build/Release-iphonesimulator/BmiCalculator.app");
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(CapabilityType.BROWSER_NAME, "iOS");
        capabilities.setCapability(CapabilityType.VERSION, "6.1");
        capabilities.setCapability(CapabilityType.PLATFORM, "Mac");
        capabilities.setCapability("app", app.getAbsolutePath());

        //Create an instance of RemoteWebDriver and connect to the Appium server.
        //Appium will launch the BmiCalc App in iPhone Simulator using the configurations specified in Desired Capabilities
        driver = new RemoteWebDriver(new URL("http://localhost:4723/wd/hub"), capabilities);
    }

    @Test
    public void testBmiCalc() throws Exception {

        //iOS controls are accessed through WebElement class
        //Locate the Height & Weight textField by their accessibility labels using By.name()
        WebElement heightTextField = driver.findElement(By.name("Height"));
        heightTextField.sendKeys("181");

        WebElement weightTextField = driver.findElement(By.name("Weight"));
        heightTextField.sendKeys("80");

        //Locate and tap on Calculate button using the click() method
        WebElement calculateButton =  driver.findElement(By.name("Calculate"));
        calculateButton.click();

        //Locate all the label elements using By.tagName()
        List<WebElement> labels = driver.findElements(By.tagName("staticText"));

        //Check the calculated Bmi and Category displayed on labels
        //Label with index 8 has value of the Bmi and index 9 has the value for category
        assertEquals("24.42",labels.get(8).getText());
        assertEquals("Normal",labels.get(9).getText());
    }

    @After
    public void tearDown() throws Exception {
        //Close the app and simulator
        driver.quit();
    }
}

I really liked using Selenium WebDriver API for writing iOS tests with Appium. I can add iOS support to my existing Selenium Framework with minimal changes. Appium presently supports locating elements using the tag name (i.e type of iOS control) and accessibility labels.

Running tests in Cloud

You can also run Appium with Sauce Labs Cloud, for more details read http://sauceio.com/index.php/2013/02/announcing-appium-on-sauce-native-hybrid-ios-testing-in-the-cloud/

Overall Appium is a great tool to start with.

References:
Getting Started – http://appium.io/getting-started.html
Appium on GitHub – http://sauceio.com/index.php/2013/02/announcing-appium-on-sauce-native-hybrid-ios-testing-in-the-cloud/
Samples – https://github.com/appium/appium/tree/master/sample-code
Wiki – https://github.com/appium/appium/wiki
Google Group – https://groups.google.com/forum/?hl=en&fromgroups=#!forum/appium-discuss

Data Driven Testing with Selenium IDE

Selenium IDE does not have in-built features to create data-driven tests. However there are multiple options available in the form of Selenium IDE User Extension or Add-On for creating Data Driven tests.

This post will explore using a Selenium IDE Add-on called Sel Blocks to create Data Driven tests on a sample BMI Calculator application. This is a simplest option available for Selenium IDE for data-driven tests.

The Sel Blocks Add-on provides various flow control elements such as conditional handling, looping, variables and data-driven testing in Selenium IDE tests.

Setup
Install the Sel Blocks for Selenium IDE Add-On using the Add-On Manager in Firefox from https://addons.mozilla.org/en-US/firefox/addon/selenium-ide-sel-blocks/?src=search

Creating Data Driven Tests
First we need to identify test data for the script. The Sel Blocks Add-on needs the test data in XML format. Create a XML file with following format:

<testdata>
	<vars height="160" weight="45" bmi="17.6" bmi_category="Underweight" />
	<vars height="168" weight="70" bmi="24.8" bmi_category="Normal" />
	<vars height="181" weight="89" bmi="27.2" bmi_category="Overweight" />
	<vars height="178" weight="100" bmi="31.6" bmi_category="Obesity" />
</testdata>

You can have data rows defined as <vars> element under the root element <testdata>. In <vars> element you can define all the parameters needed for the test. Create the following script in Selenium IDE:

SelIDE

How it works
In this test the type and verifyValue commands are parameterized by substituting values from the test data specified in above XML file.

The forXml command of Sel Blocks is supplied with the name of XML file where test data is stored. In this example path of data.xml file is passed to the forXml command.

When this test is executed, Sel Blocks loads the content of XML file in memory and executes the script for number of times <vars> element present in the XML file. In this example it will execute the test for four times.

For all the attributes mentioned in <vars> element, Sel Blocks create internal variables that we can substitute as Selenium command parameters.

You can analyse the Selenium IDE Log tab for  results. If the expected data and actual data do not match, an error is reported in the Selenium IDE Log tab.

There’s more
You can also use datadriven user extension to create Data Driven tests. You need to install flowControl andinclude user extensions to use the dataddriven extension. Sel Blocks is easier option as it does not have dependency on any other extension. For more info visit http://wiki.openqa.org/display/SEL/datadriven

This post covers Data Driven testing with Selenium IDE. If you are looking for Data Driven testing with Selenium WebDriver, grab my book Selenium Testing Tools Cookbook published by PacktPub

Implementing ATDD/BDD with QTP – Rough Cuts

Recently I started working with SpecFlow.NET a very popular BDD tool available for .NET. It does a impressive job of automating acceptance testing in agile projects.

Out of curiosity I started a small proof-of-concept to build a similar framework with HP QTP, a popular GUI automation tool. This post covers the basics of the framework I built and as I indicated in the title, this framework does not have all the features like SepcFlow or Cucumber. This is just a rough implementation to prove that tools like QTP can also be used in BDD.

There is enough written about Behaviour Driven Development (BDD), and you can know more about it from Dan North’s legendary article http://dannorth.net/introducing-bdd/ and Wikipedia entry http://en.wikipedia.org/wiki/Behavior-driven_development

Behaviour Driven Development focuses on obtaining a clear understanding of desired application behaviour through discussion with stakeholders. In a nutshell using BDD technique you author automated tests in the language of the business while maintaining a connection to implemented system. Users describe features and scenarios to test these features in plain text files using Gherkin language in Given, When and Then structure. For more information on Gherkin language see http://en.wikipedia.org/wiki/Behavior-driven_development and https://github.com/cucumber/cucumber/wiki/Gherkin

  • Given [Precondition]
  • When [Actor + Action]
  • Then [Observable Result]

In BDD process starts with users of the system and development team discussing features, user stories and scenarios. These are documented in feature or story files using the Gherkin language. Developers then use the red green re-factor cycle to run these features using the BDD framework then writing step definition files mapping the steps from scenarios to the automation code and re-running, until all the acceptance criteria are met.

Here is a list of some popular BDD tools:

  • Cucumber, RSpec – Ruby
  • Cucumber-JVM, JBehave – Java
  • SpecFlow.NET – .NET

This example demonstrates acceptance testing of Fund Transfer feature from an on-line banking application using BDD. Using the fund transfer application a bank account holder can transfer or wire money to a registered payee. There are some validations around this feature which are captured in the specification.

Step 1 – Creating Feature Files

The first step is to create a feature file. A feature file defines specifications using Gherkin language for a feature under development. It’s a simple text file which starts with the feature description in a user story format. Then acceptance criteria is listed in the form of scenarios in the feature file. In below feature file, sample scenarios are described to validate the fund transfer application:

Feature: Customer Transfers Fund
	As a customer,
	I want to transfer funds
	so that I can send money to my friends and family

Scenario: Valid Payee
	Given the user is on Fund Transfer Page
	When he enters "Jim" as payee name
	And he enters "100" as amount
	And he Submits request for Fund Transfer
	Then ensure the fund transfer is complete with "$100 transferred to Jim successfully!!" message

Scenario: Invalid Payee
	Given the user is on Fund Transfer Page
	When he enters "Jack" as payee name
	And he enters "100" as amount
	And he Submits request for Fund Transfer
	Then ensure a transaction failure message "Transfer failed!! 'Jack' is not registered in your List of Payees" is displayed

Scenario: Account is overdrawn past the overdraft limit
	Given the user is on Fund Transfer Page
	When he enters "Tina" as payee name
	And he enters "1000000" as amount
	And he Submits request for Fund Transfer
	Then ensure a transaction failure message "Transfer failed!! account cannot be overdrawn" is displayed

Feature files are kept in a Feature folder in QTP script folder. Separate feature files are created for each feature based on number of features under test. The feature file should use .feature extension.

Test data values needed to execute steps can be embedded using double quotes. In above feature there is a step which says When he enters “Jim” as payee name. Here name of the payee is quoted.

Step 2 – Creating Step Definition File
A step definition file is created which maps the steps from a feature file to the automation code. Here is a step definition file implemented for fund transfer feature as follows:

'//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
' Script Name:	FundTransferStepDefs.vbs
' Author:		Unmesh Gundecha
'
' Description:  This file contains step definitions for Fund Transfer Feature
'				While defining function, please specfiy Step definition as comment above the function name in square brackets []
'//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

'[Given the user is on Fund Transfer Page]
Function GivenUserIsOnFundTransferPage()
 	GivenUserIsOnFundTransferPage = Browser("Browser").CheckProperty("title","Fund Transfer Page")
End Function

'[When he enters "name" as payee name]
Function WhenUserEneteredIntoThePayeeNameField(strPayeeName)
	Browser("Browser").Page("Fund Transfer Page").WebEdit("payeeTextBox").Set strPayeeName
End Function

'[And he enters "amount" as amount]
Function AndUserEneteredIntoTheAmountField(amount)
	Browser("Browser").Page("Fund Transfer Page").WebEdit("amountTextBox").Set amount
End Function

'[And he Submits request for Fund Transfer]
Function AndUserPressTransferButton()
	Browser("Browser").Page("Fund Transfer Page").WebButton("Transfer").Click
End Function

'[Then ensure the fund transfer is complete with "message" message]
Function ThenFundTransferIsComplete(message)
	ThenFundTransferIsComplete = Browser("Browser").Page("Fund Transfer Page").WebElement("message").CheckProperty("innerText", message)
End Function

'[Then ensure a transaction failure message "message" is displayed]
Function ThenFundTransferIsFailed(message)
  ThenFundTransferIsFailed = Browser("Browser").Page("Fund Transfer Page").WebElement("message").CheckProperty("innerText", message)
End Function

For each unique step in the feature file, a function is written which calls QTP code as per the behaviour specified in the step. This file is implemented as a function library file. These functions are mapped to steps using a special commenting standard. For example there is a step When he enters “Jim” as payee name in feature file. For this step a WhenUserEneteredIntoThePayeeNameField() function is defined in the step definition file . A special comment is written on top of the function declaration. This will tell driver script to map the matching step from feature file to this function.

'[When he enters "name" as payee name]
Function WhenUserEneteredIntoThePayeeNameField(strPayeeName)
	Browser("Browser").Page("Fund Transfer Page").WebEdit("payeeTextBox").Set strPayeeName
End Function

Step 3 – Creating Driver

The BDD_Driver script is core of this framework. This script reads feature file and step definition file and creates a map of steps along with their corresponding functions. It then executes scenarios from feature file using this map.

QTP BDD_Framework Architecture
QTP BDD_Framework Architecture

BDD_Driver script also provides test data embedded in a step from feature file to the function called from step definition file. A step definition function internally calls QTP code which runs the automated step on the application emulating user behaviour.

'//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
' Script Name:	BDD_Driver
' Author:		Unmesh Gundecha
'
' Description:  This is the main script of QTP-BDD Framework. This drives the execution of features and steps
'				Script first reads Step Definition File and creates a dictionary of available steps and functions.
'
'				For executing a Feature file it refer the dictionary matching steps from feature file and calling the respective function
'				While calling the step function it passes the test data embedded in Feature file steps to the function
'//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	Option Explicit

	Dim arrStepDefs, objStepDict, intLineIdx, strLine, strNextLine, arrFeatureFile, intScenarios, strArgs, varResult
	Dim strKey, arrArgs, strTestStep, strStepStatus, intCnt

	'Open the Test Application, by directly providing URL, QTP will launch the Browser and navigate to the specified URL
	SystemUtil.Run "http://dl.dropbox.com/u/55228056/fundTransfer.html"

	'Go through the Step Definition file and create dictionary of step definition and corresponding functions
	arrStepDefs = Split(DotNetFactory.CreateInstance("System.IO.File").ReadAllText(PathFinder.Locate("FundTransferStepDefs.vbs")),vbCrLf)
	Set objStepDict = CreateObject("Scripting.Dictionary")
	For intLineIdx = 0 To UBound(arrStepDefs)
		strLine = arrStepDefs(intLineIdx)
		If strLine <> "" Then
			If Left(strLine,2) = "'[" And Right(strLine,1) = "]" Then
				strLine = Replace(Replace(strLine,"'[",""),"]","")
				strLine = ParseLine("Step", strLine)
				strNextLine = Trim(arrStepDefs(intLineIdx+1))
				strNextLine = Replace(Replace(strNextLine,"Function",""),"Sub","")
				strNextLine = Mid(strNextLine,1,InStr(strNextLine,"(")-1)
				objStepDict.Add strLine, strNextLine
			End If
		End If
	Next

	'Read Feature file and match step definitions in objStepDict
	arrFeatureFile = Split(DotNetFactory.CreateInstance("System.IO.File").ReadAllText(PathFinder.Locate("FundTransfer.feature")),vbCrLf)
	For intLineIdx = 0 To UBound(arrFeatureFile)
		If InStr(arrFeatureFile(intLineIdx),"Feature:") <> 0 Then
			Print "Feature: " & Trim(Replace(arrFeatureFile(intLineIdx),"Feature:",""))
			intScenarios = 0
		ElseIf InStr(arrFeatureFile(intLineIdx),"Scenario:") <> 0 Then
			intScenarios = intScenarios + 1
			Print vbTab & "Scenario: " & Trim(Replace(arrFeatureFile(intLineIdx),"Scenario:",""))
		Else
			strArgs = ""
			varResult = ""
			strLine = Replace(Trim(arrFeatureFile(intLineIdx)),vbTab,"")
			If strLine <> "" Then
				strKey = ParseLine("Step",strLine)
				'After a step is found in dictionary generate the function call using the test data embedded in step from feature file
				If objStepDict.Exists(strKey) Then
					'Get Test Data Values from Feature File Steps and create an Argument Array
					If ParseLine("Args",strLine) <> "" Then
						arrArgs = Split(ParseLine("Args",strLine),";")
						For intCnt = 0 to UBound(arrArgs)
							strArgs = strArgs & "arrArgs(" & intCnt & "),"
						Next
						strArgs = Mid(strArgs,1,Len(strArgs)-1)
						strTestStep = "varResult = " & objStepDict(strKey) & "(" & strArgs & ")"
					Else
						strTestStep = "varResult = " & objStepDict(strKey)
					End If
					'Execute the function call
					Execute(strTestStep)
					If varResult <> "" Then
						If varResult Then
							strStepStatus = " [PASS]"
						Else
							strStepStatus = " [FAIL]"
						End If
					End If
					Print vbTab & vbTab & strLine & strStepStatus
				Else
					If InStr(strLine,"Given") <> 0 Or InStr(strLine,"When") <> 0 Or InStr(strLine,"Then") <> 0 Or InStr(strLine,"And") <> 0  Then
						Print vbTab & vbTab & strLine & " [PENDING]"
					Else
						Print vbTab & vbTab & strLine
					End If
				End If
			End If
		End If
	Next

	Print vbCrLf & "Total " & intScenarios & " Scenarios Executed!!"

	Function ParseLine(ByVal strWhatToParse, ByVal strLine)
		Dim objRegEx, objMatches, objMatch, strResult
		Set objRegEx = New RegExp
		objRegEx.Pattern = "\""(.*?)\"""
		objRegEx.IgnoreCase = True
		objRegEx.Global = True
		Set objMatches = objRegEx.Execute(strLine)
		For Each objMatch in objMatches
			If strWhatToParse = "Step" Then
				strResult = strResult & Replace(strLine,objMatch,vbNullString)
			ElseIf strWhatToParse = "Args" Then
				strResult = strResult & Replace(objMatch,"""","") & ";"
			End If
		Next
		If strResult <> "" Then
			If strWhatToParse = "Step" Then ParseLine = strResult
			If strWhatToParse = "Args" Then ParseLine = Mid(strResult,1,Len(strResult)-1)
		Else
			If strWhatToParse = "Step" Then ParseLine = strLine
			If strWhatToParse = "Args" Then ParseLine = ""
		End If
	End Function

This code might look little odd due to the language constraints that we have with VBScript. However it proves that BDD is possible with tools like QTP, however a better solution can be built in detail. Here is a sample report generated by the BDD_Driver

Next steps:
This is not complete framework and needs to be enhanced further as a mature BDD framework. Here are some key items that can be added/improved in next iteration:

  • Support multiple Feature and Step Definition files
  • 100% Gherkin syntax support
  • Suggest step definitions where functions are not implemented for steps in log/report
  • Support for ignoring steps where step definition is not implemented
  • Support for reading tabular data from steps
  • Report Generation like SpecFlow

Comparison with Keyword Driven testing
Implementing tests with BDD is pretty much similar to Keyword driven testing. In Keyword driven testing, Keywords or Actions are defined and mapped to functions which execute code related to the Keyword. Tests are written in tabular format which is easy to understand for users without having knowledge of the test tool or automation code. The driver script orchestrates the entire test execution.

In BDD, steps are written in a feature file can be compared to Keywords or actions and step definitions are the underlying functions created for the Keywords. However tests are expressed in a non tabular format, in a more natural plain text or domain specific language.

I’ll be happy to know your comments or suggestion to improve this further.