You are on page 1of 247

User Guide

The Ranorex Automation Framework is used to automate all kind of Windows applications and web sites.

Getting Started Test Automation Tools

Lesson 1: Getting Started Ranorex Studio


Lesson 2: Ranorex Modules - Capture & Replay with Ranorex
Test Actions Recorder
Lesson 3: Data-Driven Testing UI Mapping with Ranorex
Repository
Lesson 4: Ranorex Test Suite

Ranorex Library Technology Instrumentation


Ranorex Code Examples Learn more about technology dependent
instrumentation and how to troubleshoot
See how to use Ranorex API in order to
object recognition issues using the
write code modules or to extend recording
information below:
modules with user specific test automation
code.
Flash/Flex Testing
API Documentation Testing of Java Applications
Ranorex comes with an automation library.
Qt Testing
See detailed interface documentation.
Testing of Legacy Applications
General Troubleshooting

Working with 2.X Projects in 3.X Test Suites


Learn how to use your 2.X recordings and code modules for Ranorex 3 test cases within the new test suite editor.

User Guide Overview

Ranorex Studio - The Layout


Lesson 1: Getting Started
Lesson 2: Ranorex Modules - Test Actions
Lesson 3: Data-Driven Testing
Lesson 4: Ranorex Test Suite
Lesson 5: Ranorex Recorder
Lesson 6: UI Mapping with Ranorex Repository
Lesson 7: C ode Modules
Lesson 8: Reporting
Lesson 9: Ranorex Spy
Lesson 10: RanoreXPath Editor
C ode Examples
Data C onnectors
Instrumentation Wizard
Working with 2.X Projects in 3.X Test Suites
Technology Instrumentation

Page 1 of 247
RanoreXPath
Ranorex UI Adapter
Android Testing
Web Testing
Ranorex Studio IDE
Visual Studio Integration
System Requirements
64-bit Platforms
Remotely Working with Ranorex
Silent Installation of Ranorex
Licensing
FAQ

C opyright © 2012 Ranorex

Page 2 of 247
Ranorex Studio - The Layout
This initial lesson will introduce the main environment from Ranorex studio.

Before you start creating your first test case with Ranorex Studio you should know about the main views and
layout of Ranorex Studio.

Ranorex Studio main views

#1 - Project View
A Ranorex Studio project is based on files and uses the same project file format as Microsoft Visual Studio 2008.
The project view shows all files and references currently associated with the project. A Ranorex Studio project
can have the following type of items:

Test Suite  Represents the projects test suite (*.rxtst)


Module Group Represents the projects module groups (*.rxtmg)
Repository Used to manage UI elements (*.rxrep)
Recording
Represents an automation module based on capture/replay (*.rxrec)

C ode Files Any type of C # or VB.NET code; typically used to create code based automation modules

The project view is mainly used to add new items like Recordings, Repositories, Module Groups, or C ode Modules.

#2 - Module Browser
The 'Module Browser' view lists all available modules (C ode Modules & Recording Modules) based on the project's
code files and module groups based on the projects module group file. In addition it shows all the variables
defined by a module or module group. The view is mainly used to drag and drop and to reuse automation
modules and module groups within the test suite view.

Specify folders (e.g. for recording files) within the project's view to group modules. In order to find already
existing modules use the module browser's search field.

#3 - File View
When double-clicking a file in the 'Project View' or a module in the 'Module Browser', the associated file will be
openend in the Studio's file view. This view is mainly used for the actions shown below.

Page 3 of 247
Working with the project's test suite Working with the project's module groups

Creating or adapting a recording module Working with the repository

Writing code modules Viewing a test report

C opyright © 2012 Ranorex

Page 4 of 247
Lesson 1: Getting Started
In this lesson you will gain a deeper understanding of the recorder. The first recording will capture a set of user
actions (mouse clicks, keystrokes) done while working with the tool KeePass which is delivered with Ranorex
Studio. KeePass is a widely available and easy to use open source password manager.

The easiest way to create a first test with Ranorex is to record a manually executed test scenario. The recorded
actions like mouse clicks or keyboard actions are the base for building a robust test case. In this lesson you will
learn about:

Preparing to Record User Actions


System Under Test: KeePass Password Safe
Recording a Test
Analyzing Recorded Steps
Executing the Test

Preparing to Record User Actions


Before you start recording you need to ensure that your system under test (SUT) is ready to start with the
manual test execution. In addition, consider the following points in order to avoid too much work in cleaning up
the recording and the repository afterwards.

Do not run multiple instances of your application under test if that is not part of the test case itself.
By default mouse movements are not recorded. For this reason please also perform a mouse click in
situations like when navigating through menus. Note: Read more about how to activate mouse movement
recording in Lesson 5: Ranorex Recorder - Recorder Hotkeys.

System Under Test: KeePass Password Safe


As was mentioned in the overview section, this tutorial uses the open source tool KeePass to demonstrate
Ranorex functionality for automating an application in order to build up a testing framework. KeePass is a
powerful and easy to use tool for managing passwords and other private information. For more information about
KeePass, please have a look at the following URL: http://keepass.info.

Open source tool KeePass

Since version 3.3, KeePass is included with Ranorex Studio along with a sample database file.

Note: The password to open this database file is 'rx'.

On the start screen of Ranorex Studio you'll find a 'Sample' button which also includes a sample test suite project
that handles some test cases within the KeePass application. You can have a closer look at that in Lesson 4:
Ranorex Test Suite - General Structure of a Test Suite and its Test C ase.

Page 5 of 247
Recording a Test
In the following section you will create a new Ranorex Test Solution and record the process for adding an entry to
KeePass.

Start Ranorex Studio and open the empty recording file.

Open Ranorex Studio by choosing Start > Programs  > Ranorex > Ranorex Studio. C lick the ‘New Test
Solution…’ button to create a blank test suite project.

Ranorex Studio Start Page - creating a new test


solution

Specify programming language and project name

In the categories box select C # and in the templates box select the Ranorex C # Test Suite item. Next specify a
name and a location for your new test suite project.

C lick the 'C reate' button and a new test suite project opens.

New Ranorex Test Suite containing one test case


using an empty recording

Within the test suite view, the template already contains a single test case which uses an empty recording. In
order to start recording simply open 'Recording1' by double-clicking the recording within the test suite view.

Page 6 of 247
Empty Recording

Start recording a test  for the KeePass application.


Note: It's recommended to copy the KeePass application folder from the sample directory within the Ranorex
installation folder (<Ranorex Installation Folder>\Samples\KeePassSample\C #\KeePassTestSuite\KeePass) to
your projects folder as by default you do not have write access to the program folder which is necessary to save
the database handled by KeePass.

You can open the project folder by right-clicking the project in the 'Projects' view and choosing 'Open Folder in
Explorer' from the context menu

Open project folder in explorer to copy the sample


application to the project folder

C lick the 'Record' button in order to start. The Recorder assists you in preparing the application under test.
Simply select 'Run an Application' and specify the directory and file name of the application under test. After
copying the KeePass application folder to your project folder, you can set the 'File Name' by choosing the file
'KeePass.exe' using the 'Browse' button.

Page 7 of 247
New Recording dialog - Ranorex automatically starts
the specified application

C lick on 'Start' in order to record the test. The KeePass application opens and the Ranorex Recorder starts
running.

Recording actions for the KeePass application

Enter the default Password.

C lick on the text field next to the 'Master Password' check box
Type in the default password ('rx')

KeePass application

Open the 'Add new Entry' Form.

C lick on 'Edit' in the main tool bar


C lick on the 'Add Entry' menu item

Page 8 of 247
KeePass application with sub menu 'Edit' (Menu item
'Add Entry' is selected)

Add a new entry to the KeePass application.

C lick on the 'Title' text box and type in 'WordPressDemo'


C lick on the icon button (with key symbol)
C hoose any icon (e.g. the second one)
C lick on 'C lose'

C lick on the 'User name' text box and type in 'admin'


C lick on the 'Password' text box
C lick again with the right mouse button
C hoose 'Select All'
Type in 'demo123'
Repeat the same for 'Repeat' text box
C lick on the 'URL' text box and type in http://bitly.com/wp_demo
C lick the 'Expires' button on the right (watch symbol)
C hoose '1 Year' menu item

C lick on 'OK' button

KeePass form for adding a password entry

Page 9 of 247
KeePass form for choosing an icon

KeePass expiration sub menu

Validate the result.


After adding a new password entry, a new row is added to the KeePass grid holding the recently entered item.
C lick the 'Validate' button within the 'Recording' toolbar to check whether the entry appears in the grid or not.
Move the mouse pointer to the grid (i.e. the first cell) and wait a moment until the underlying UI element is
highlighted.

KeePass form with highlighting frame for validation

The dialog shows all available attributes for the given UI element to check. Just click the 'OK' button in order to
accept the preselected 'Text' attribute.

Page 10 of 247
Ranorex validate window

Delete added item and close application.


In order to finish the recording scenario select the added item within the data grid and delete it from the list by
pressing the 'DEL' button on your keyboard.

Finally press the save button in the toolbar and close the application by clicking the close button.

Screenshot indicating the save button in the tool bar

Stop the recording by pressing the 'Stop' button in the recorder tool bar.

Analyzing Recorded Steps


The Recorder created single steps for each operation you performed on the application. These steps are
represented within the actions table. In addition each action item is connected to a repository item which
represents a UI element (text boxes, radio buttons, buttons, etc.) used during the recording.

Recorded steps shown within the actions table

You can read more about different action types within Ranorex Recorder in Lesson 5: Ranorex Recorder -
Additional Editing Options.

Executing the Test


Page 11 of 247
In order to execute the recorded test you need to switch back to the Ranorex Test Suite file. Just click on 'Run' to
execute the test suite with your first recorded test.

During the execution Ranorex simulates all user actions (mouse movements and keyboard events) in order to
test the application in the same way a tester would successfully do it.

Start the test by clicking the 'Run' button

Reporting

After executing the test, Ranorex Studio automatically opens the generated test report file (*.rxlog) which shows
whether the test run was successfully or not.

Test run succeeded Test run failed

In order to force an error as shown in the right picture above, simply modify the expected value used in the
validation step of the recording (e.g. 'Typo3Demo' instead of 'WordPressDemo').

Force an error by changing the expected value of


the validation step

Now the test automation executable is also available within your project folder. To run the test suite without
starting Ranorex Studio, simply double-click the executable file.

Note: In order to run the test suite project on an external machine it is required to have the executable (*.EXE)
as well as the test suite file (*.RXTST) in the same directory at the target machine. If your Ranorex Studio
solution consists of more than one project, you need to ensure that the library (*.DLL) files are also part of the
same directory.

'MyFirstTestProject.exe' located within the build


folder of the project

By default the report files are also generated within the same directory. Further information on changing the
report folder can be found in Lesson 4: Ranorex Test Suite - Test Suite Settings.

Page 12 of 247
Read more about alternative ways to run the test suite from the command line or with the standalone test suite
runner in Lesson 4: Ranorex Test Suite - Running Tests without Ranorex Studio.

C opyright © 2012 Ranorex

Page 13 of 247
Lesson 2: Ranorex Modules - Test Actions
This lesson will show you the benefits of splitting your recordings into smaller pieces (to provide for reusability)
and how your projects can be easily assembled afterwards using drag and drop functionality in Ranorex Studio.

Refactoring: Why you should Separate Recordings


The ease of recording user actions encourages one to record all test cases without thinking about reusability. But
in the long run, this could increase the effort in test automation maintenance. For this reason you should separate
a recording into smaller reusable recording modules as suggested by the keyword driven methodology. Within
the following section you learn how to separate the existing recording into smaller pieces, so that they can be
used within other test cases too.

Identifying Modules
In your first recording you did the following from a keyword driven perspective:

Started the application KeePass


Logged in
Added a new entry
Set the attributes for title, username, password, URL
C hose an icon
Set the expiration value

Validated the existence of the newly created entry in the grid


Deleted the entry
Saved the changes
C losed the application

In order to split recordings into smaller automation modules, select thematically related recorder items and use
the context menu item 'New Recording From Selection'. Within the underlying recording, three actions for doing
the log in should be selected and moved into a new recording named 'LogIn'. These three actions are a click on
the password field, a key sequence on the password field and finally a mouse click on the OK button.

Move first action to a new recording Create a new recording named


'LogIn'

Also select and move all items within the recording used to add a new entry named 'AddEntry.rxrec' in the same.

Repeat the previous steps to create modules for 'ValidateEntry', 'DeleteEntry', 'SaveDB' and for
'C loseApplication'.

Also rename the initial recording file (with only one recorded item left for starting the application) from
'Recording1.rxrec' to 'StartSUT.rxrec'. In the end you should have seven separated new recording modules.

After splitting the initial recording into smaller test actions, the Ranorex Module Browser also contains the new
modules. Now simply use the drag and drop feature to combine these modules within the test case.

Page 14 of 247
Use the drag and drop feature to specify your test
case within the test suite view

Separating a recording into smaller modules is the first step in building robust and reusable automation modules.
In addition replace constant values used within these modules with variables in order to enable parameterization.
Read more about how to use variables in Lesson 3: Data-Driven Testing.

C opyright © 2012 Ranorex

Page 15 of 247
Lesson 3: Data-Driven Testing
In this lesson you see how tests can be done using internal (simple data tables) or external data sets (Excel files,
C SV files, SQL Databases) to do a data-driven automated test. You can use variables in recordings and even in
the repositories which are connected to internal or external data sources. Additionally, you will see how a select
action can be invoked for UI elements which are not visible by default in order to ensure your data-driven test
case does not fail.

When you test an application it might be necessary to run the same test with different input data. Next you'll learn
about:

Using Variables within Recordings


Using Variables within the Repository
C reating Test Data
C ombining Variables with Test Data
C ombining Variables with Parameters
Invoking Actions: Selection
Executing Data Driven Test

Using Variables within Recordings


According to the KeePass application we can identify six variable input actions:

Title (WordPressDemo)
Username (admin)
Password (demo123)
URL (http://bitly.com/wp_demo)
Expires (1 Year)
IconIndex (1)

All these input actions are done within the 'AddNewEntry' recording. You need to open the recording file and
identify the actions which have to be variable.

To make the input of the title variable, open the combo box as shown below and select 'As new Variable' to
create a new variable.

Create a new variable for a key sequence action


item

Create a new variable

Page 16 of 247
Specify the variable name and the default value which is automatically set to the same value as it was recorded
initially. If you want to alter the name or the default values, simply open the variables dialog as described in
section Using Variables within the Repository.

Note: Please do not use variable names which are already in use by a recording or code module.

Repeat the previous step which makes the key sequence action used to set the value of the title field variable,
and also create the variables 'varPassword', 'varUsername' and 'varURL' for the specific actions.

Using Variables within the Repository


Within the recording 'AddNewEntry' the variables 'varTitle', 'varUsername', 'varPassword' and 'varURL' are used
for key sequence actions.

To make a click action data driven - for example selecting a context menu item for expires-constants like 1 week
- you need to define a variable used for identification within a RanoreXPath expression.

Select that action item within the 'AddNewEntry' recording which simulates a click on a menu item and open the
context menu as shown below. C lick on 'Make Item Variable...' to open the RanoreXPath editor.

'Make Item Variable' menu item from context menu


in Recorder

Typically the menu item for the 'Expires Date' in KeePass application is identified by the accessible name
attribute. Now you can define a new variable for the attribute text by clicking the button on the right.

Create a new variable for the expires menu item

When looking at the repository, you see that the item pointing to the menu item is now using the variable within
the path expression previously specified.

Renaming repository items

Also rename the repository item 'MenuItem1Year' to 'MI_Expires' to clarify that this repository element is not
pointing to a specific menu item anymore but instead uses a variable to choose one of the menu items in a data-
driven way.
Repeat the same procedure to add a new variable 'varIconIndex' into the repository item which is connected to
the icon list view.

The recording 'AddNewEntry' now uses six variables. Four of them are used for key sequences directly within the
recording while the others are used within the repository. To get an overview about all variables used within the
recording simply click the 'Variables' button as shown below.

Page 17 of 247
Open the recording's variable dialog

Variables currently used by the recording and


repository

Creating Test Data


The sample recording now uses six variables. In this section you will learn how to connect a simple Excel table to
provide the values for these variables. To create a new Ranorex data source you need to open the test suite
view.
Select the test case which uses the 'AddNewEntry' recording and open the 'Data Source' dialog by clicking the
'Manage Data Sources' button in the tool bar.

Open the 'Manage data sources ...' dialog

Assuming someone is still keeping his passwords in an excel-file, the following example could be helpful in more
safely managing the information.
This Excel file contains the fields Title, Username, Password, URL, Expires and IconIndex.

Use an Excel file for data-driven testing

Now create a new data connector by clicking on 'Use Excel file...'.

Page 18 of 247
Create a new Excel connector

Specify the filename from the Excel file

For further information about different Ranorex data connector types hava a look at Data C onnectors.

Combining Variables with Test Data


In order to combine your Excel file with the current test case - and finally with the 'AddNewEntry' recording which
is used by the test case - you need to open the data binding dialog using the context menu as shown below.

Page 19 of 247
Open data binding dialog

Now you can connect each column specified within the data table with variables used by the test case. You can
also map multiple variables to one data column. You currently only have variables specified within the
'AddNewEntry' module.

Connect data columns with module


variables

Combining Variables with Parameters


Parameters can be useful when automated tests are executed under different environment-related conditions. An
automated test in Windows 7, for example, may need different path values in comparison to a test execution in
the Windows XP operating system. Parameters can be created in Ranorex Studio in order to be connected with
variables.

In addition to typical test data specified within data tables as shown before, a test suite and its test cases allow
you to declare global and local parameters. These parameters can also be bound to module variables. This type
of data driven execution helps to specify such things as environment-related attributes as the following example
describes.

The test case starts with a recording module called 'StartSUT'. The recording only contains a single action item
used to start the KeePass application. Open the recording and create a new variable called 'varApplicationPath'.

Create a new variable for the execution path of


system under test

The execution path of the system under test has to be declared as a global parameter on the test suite level in
order to combine it with multiple test cases of the test suite. Use the context menu within the test suite view and
open the parameters dialog as shown below.

Open global parameters dialog


Page 20 of 247
Define a new global parameter for the test suite

Specify a new parameter name by clicking in the first cell of the column 'Name'. Now specify a value for the new
parameter. Just copy and paste the execution path from the default value shown within the variables dialog of the
recording 'StartSUT'. C lick 'OK' to apply the changes and to close the dialog. Read more about how to open a
recording's variable dialog in Lesson 5: Ranorex Recorder - Recorder Variables.

Now you are ready to combine the global parameter with the variable created within the recording before. Open
the test case's data binding dialog the same way you did previously for combining variables with the data table.

Bind global parameter to the variable used within


recording 'StartSystemUnderTest'

Before you execute the data driven test case, you have to make sure that the values specified within the Excel
file can be used correctly within the 'AddNewEntry' recording. The values for the title, username, password, URL
and expiration will not cause any problems during automation. C onsidering a more advanced situation such as
selecting an item from a list view which is not visible by default; there will be a problem because of the current
visibility state of the item. This situation will be handled in the next section.

Invoking Actions: Selection


KeePass offers a list of icons which can be accessed via the button next to the label 'Icon':

Page 21 of 247
Button to open the Icon Picker

Form for choosing an icon for a password entry

Icons with an index of 0 to 49 are visible without using the scroll bar so icons with indexes lower than 49 could
even be accessed easily when using a data-driven approach. In order to select an icon with a higher index (e.g.
66 for the US dollar icon) in an automated way, a simple click on an invisible item would fail. It is recommended
to add an 'Invoke Action' to select the icon regardless of the visibility of the item in the listview.

First of all an additional action should be added to the recording right before the action representing the click on
the icon.

Select one action before the clock action and click the 'Add New Action' button as shown below.

Page 22 of 247
Adding a new 'Invoke Action' to the recording

After adding the new item you need to specify for which repository element the invoke action should be used.
Simply open the 'Select Repository Item' dialog as shown below and select the 'IconItem'.

Open the 'Select Repository Item' dialog by clicking


on the highlighted button and choosing
'ListItem_Icon' from the repository

After assigning the repository item to the invoke action, the recorder presents the methods suitable for the role
list item. The role list item shows a 'Select' method which you can chose as seen in following figure.

Choose 'Select' method

Also delete the initially recorded mouse click action (action item \#7 shown in previous figure) because now the
recording uses the new invoke action to select the list item instead of the click action.

Executing Data Driven Test


Note: Before executing the test suite, it's necessary to make the added entry used for recordings 'ValidateEntry'
and 'DeleteEntry' variable as you learned in the previous sections.
Now switch back to the test suite view and start your data driven test by clicking the 'Run' button.

Report file showing two iterations of the test case

After executing the test suite the report file shows the results for each iteration. The summary chart counts each
iteration as a single test case run.
Page 23 of 247
C opyright © 2012 Ranorex

Page 24 of 247
Lesson 4: Ranorex Test Suite
As was already mentioned in Lesson 2: Ranorex Modules - Test Actions, it is recommended to separate a test
case into reusable and parameterizable test automation modules. Within the Ranorex test suite you can not only
easily create new test cases by combining already existing automation modules - you can also specify global
parameters and data connectors to set up data-driven test cases.

Within the following lesson you will learn about:

Test Suite Editor


Module Group Editor
General Structure of a Test Suite and its Test C ases
Running a Test Suite
Running Tests without Ranorex Studio
Test Suite Settings
Test C ase Settings

Test Suite Editor


After the creation of a new test suite project, a Ranorex Studio project automatically contains a
<ProjectName>.rxtst file.
By default the test suite file is open automatically.

Ranorex Test Suite file

Looking on the project created during the lessons 1 through 3 you can now create a new test case based on the
existing modules. To open up the test suite, you can double-click the *.rxtst file or use the 'View Test Suite'
button shown in the toolbar panel.

Page 25 of 247
Ranorex Studio tool bar

Add a New Test Case


You can add a new test case by clicking the 'NEW' button. Depending on the current item selection of the test
suite you are allowed to add different types of test suite elements. A test suite can be made up of the following
items:

Test cases
Recording modules
C ode modules
Module groups
Folders

Select the 'Test C ase' item to create a new test case at the current position.

Add new test case

Note: Within a test suite, test cases can be added to different layers. A test case can also be added as a child to
an existing test case or to a folder item.

The newly created test case will be used for validating the correctness of KeePass version number so the name of
the test case should be changed. Select and click on the test case and rename it to 'TC \_ValidateVersionNumber'.

Rename the test case

Reuse of Existing Modules

Now you are ready to reuse two existing record modules from the Ranorex Module Browser View.

You can simply drag and drop items from the module browser into the test case or you can add new or existing
items using the context menu as shown.

Page 26 of 247
Add an existing recording module

Select 'StartSUT' module from the list

Press 'OK' to add the record module to the test case.

Repeat the steps to add the record items 'LogIn' and 'C loseSUT' to the test case.

Insert a New Recording Module


For now the test case only covers the starting of the application under test, logging in and closing of the
application under test using three existing modules.

In order to validate the version number of the KeePass application, you can create a new recording module to be
used in the test case.

Use the context menu again, but this time to insert a new recording into the test case.

Page 27 of 247
Insert a new record module

Before starting the new recording, you should confirm that KeePass is running - you could start the application
manually if it is not running.

The new recording module 'ValidateVersionNumber' should cover the following steps:

open the about dialog


validate the version number
close the about dialog

Keep in mind that you need to select the 'Global Recording' option because the system under test will be started
by the reused recording module 'StartSUT'.

Newly created recording scenario

During the validation step, Ranorex automatically created a new repository item for the cell holding the version
number from KeePass - the text itself is used for identification of the cell (path). This situation would lead to a test
case failure if a version of KeePass was automated regardless the correctness of the version number. To avoid
this, the path to this cell should be modified to be more robust; additionally it should not use the version number
itself for identification.

Change attributes for identification: deselect 'text'-


attribute and select 'index'-attribute

Using the index for identification assures the accessibility of the cell even if a new version is released. To
complete this recording you could modify the validation action to use a new variable called
'varC urrentKeePassVersion' with a default value '2.19' instead of matching against the constant value. This
module variable could be bound to a new global variable 'GlobalC urrentKeePassVersion'.
Now the test case 'ValidateVersionNumber' is ready to be executed.

Use the context menu item 'Play Selected Test C ase' to run it and see whether it works or not.

Page 28 of 247
Play selected test case

Module Group Editor


Basically it can be useful to combine modules which belong together to groups to reuse them more easily.
One scenario is to combine the modules 'StartSUT' and 'LogIn' into a module group 'StartAndLogin' within the
KeePass sample project as these two modules are needed to start the system under test. The same applies to the
modules 'Save' and 'C loseSUT' which can be combined with the model group 'SaveAndC lose'.

This can be done using the module group editor.

In addition to the test suite file, the test suite project also contains a file defining the module groups existing in
the project. This module group file is generated automatically as <Project-Name>.rxtmg.

Double-clicking this file in the project view will open it in the module group editor.

Open module group editor

After creating a new solution an empty module groups file is created.

Page 29 of 247
Module group editor

You can add module groups to your project in the following ways:

Press the 'New Module Group' button in the module group editor
Use the context menu in the test suite editor to add a module group to a test case
Use the context menu in the test suite editor to group selected modules into a module group

Adding a module group to a test case using the


context menu in the test suite editor

Grouping existing modules into a new module group


using the context menu in the test suite editor

By grouping existing modules into a module group, the module group will be filled by the selected modules. When
adding a new module group, the module group is empty and can be filled with modules by using the context
menu in the module group and then adding a new or existing module.

Page 30 of 247
Adding an existing module to a module group using
the context menu

An existing module can also be added using drag and drop from the module browser or project view into the
module group in the module group editor.

Drag and drop module into a module group

To allow you a data driven approach as described in Lesson 3 - Data-Driven Testing, it is necessary to pass the
values from the data sources or parameters through the module group to the modules in the module group.
You can define data binding for modules in the module group by using the context menu item 'Data Binding...' is
shown appears by right-clicking a module group.

Open the data binding dialog for module group

The data binding dialog allows you to specify which of the module variables should be changeable from outside
the module group and which of the module variables should have constant values inside the module group.
Note: The mechanism for using constant values within module groups allows hiding module variables. This can
reduce the complexity and increases the clarity of module groups because it is not always necessary to set each
module variable individually.

Page 31 of 247
Define which module variables should get their
values passed from outside the module group and
which module variables should have constant value

After defining a module group and its data binding, it can be added to a test case the same way a module is
added.
The data binding for module groups works exactly the same way as it works for modules.

Further details about working with modules and data binding can be found in Lesson 2: Ranorex Modules - Test
Actions and Lesson 3: Data-Driven Testing.

Adding a module group to a test case

General Structure of a Test Suite and its Test Cases


In the last section you learned how to add new test cases to a test suite by combining existing modules with a
newly created recording.
To see the different ways of organizing a more complex test suite project, open the sample test suite project
'KeePassTestSuite' from the Ranorex Studio start page.

Opening the sample test suite project


'KeePassTestSuite'

This sample includes different types of elements which can be used within a test suite and covers all possible
Page 32 of 247
combinations.

Ranorex test suite structure

#1 Folder Used to group multiple test cases


Represents a test case which can contain modules, a setup or teardown region or
#2 Test case
other test cases
#3 Setup region Groups modules used to prepare a test case (e.g. start system under test, initialize a
database, etc.)
Groups modules used to clean up a test case (e.g. deleting files generated during
#4 Teardown region
test execution, closing application, etc.)
#5 Module group
Used to group several modules into a reusable set

#6 Recording module
Automation module generated by recording

#7 C ode module Automation module written in code

Setup and Teardown Regions


The setup and teardown regions are used to prepare and clean up a single test case execution.

The setup region will be executed before any other module held by the test case and should hold any modules
needed to bring the system under test in exactly the state your test can start from. A typical application of this
section is to start the application under test and log in with a user.

The teardown region will be executed when the execution of the test case has been finished, which means after
all modules have been executed, or an error has aborted the test case. The teardown region should hold any
modules needed to clean up the system under test and bring it to the original state. A typical application of this
section is to delete all added data and close the application under test.

The setup region will automatically be placed at the beginning and the teardown region will automatically be
placed at the end of a test case.

Use the context menu to specify which modules or module groups from a test case should be part of the setup or
teardown process.

Page 33 of 247
Add module to a setup region

Note: If you want to define one setup and one teardown region for a set of test cases, simply nest your test
cases as shown in the following pictur

Nested test case for a general setup and


teardown region

In order to quickly deactivate a certain module, instead of deleting it from the test case, use the context menu
item 'Disable'.

Searching For Elements


Use the 'Search' text box to find elements in the Test Suite.

Search result for text 'Add'

Running a Test Suite


To run a test suite click the 'RUN' button shown in the test suite editor's toolbar. Use the check boxes to specify
whether single test cases or a group of test cases should be part of a test suite run. C reate different test suite run
configurations using the drop-down box from the toolbar.

These test suite run configurations define if a specific test case will be executed or not.

For example one test suite run configuration can be defined where the data driven tests stored in your test suite
Page 34 of 247
will be executed and one test suite run configuration can be defined where they won’t.

Activate different test suite run configurations Add or remove test suite
run configurations

Running Tests without Ranorex Studio


As you already learned in Lesson 1: Getting Started, Ranorex Studio creates an executable file from your test
suite project. In order to execute the test suite in a runtime environment, you have to have the generated
executable (*.EXE) and the test suite file (*.RXTST) in the same directory. You can execute the test suite outside
Ranorex Studio using one of the folowing:

Ranorex Test Suite Runner


C ommand Line

Ranorex Test Suite Runner


Simply double-click the *.RXTST file from the project's output folder to open the Ranorex Test Suite Runner.

External Ranorex Test Suite Runner

You can use the Ranorex Test Suite Runner to run the test suite, execute certain test cases or just play a specific
automation module.
Additionally one can create new run configurations the same way as is done within a Ranorex Studio Project.

Running Test via Command Line


Using the following, you can execute the test suite from the command line:

<GeneratedTestSuite>.exe /<argument>

Allowed arguments:

help|?
Prints this help text.

listconfigparams|lcp
Lists all settable configuration parameters and their values.

config|cfg:<config parameter name>=<value>


Set values for configuration parameters.

reportfile|rf:<report file path>


Page 35 of 247
Sets the name (and path) of the report file. If no path is provided, the current directory is used. By default, the
filename specified in the rxtst file is used (for example: %S_%Y%M%D_%T.rxlog).

zipreport|zr
C ompresses the report (including associated files) to a single archive (".rxzlog" extension).

zipreportfile|zrf:<zip report file path>


When used with /zipreport|zr, sets the name (and path) of the compressedreport file. If no path is provided, the
path of the report file is used. If the file extension is not ".rxzlog", the extension will be replaced with ".rxzlog".
By default, the report filename specified in the rxtst file or the value of reportfile|rf is used with an ".rxzlog"
extension (for example: %S_%Y%M%D_%T.rxzlog).

reportlevel|rl: Debug|Info|Warn|Error|Success|Failure|<any integer>


Sets the minimum report level that log messages need to have in order to be included in the log file. Specify
'None' to completely disable reporting.

These levels correspond to the following integer values:

Debug=10
Info=20
Warn=30
Error=40
Success=110
Failure=120

listglobalparams|lp
Lists all global parameters and their values.

testcase|tc:<name of test case>


Runs this test case only.

testsuite|ts:<path to test suite file>


Runs the test cases defined by the test suite (rxtst) file.
By default

the rxtst file with the same name as the <TestSuiteExe> is used
or the first rxtst file in the same folder as <TestSuiteExe>.

runconfig|rc:<configuration name>
Runs the test cases of the specified configuration defined by the rxtst file. C onfigurations can be edited using
Ranorex Studio or TestSuiteRunner. By default, the currently selected run config is used.

module|mo:<module name or guid>


Runs the module with the specified name or guid. Assemblies loaded by <TestSuiteExe> and assemblies
referenced in the rxtst file are searched.

param|pa:<global parameter name>=<value>


C reates or overrides values for global parameters specified in the test suite.

runlabel|rul:<custom value>
Sets a custom runlabel for the test run.

Note: C ompressed report files (*.rxzlog) can be extracted by right-clicking them in explorer and choosing
'Extract' from context menu as well as report files (*.rxlog) can be compressed by right-clicking them in explorer
and choosing 'C ompress' from context menu.

Test Suite Settings


Open the test suite's settings dialog by selecting the context menu item 'Properties' on the test suite root node.

Page 36 of 247
General settings of a test suite Global parameters table

General Test Suite Settings

Name Specifies the name of the test suite (same as shown within the test suite editor)
Description of the test suite (same as shown within the description column of the test
Description
suite editor)
Show Progress Dialog Specifies whether a progress dialog should be shown during test suite execution or
not
Report Level Specifies the level of report shown with the report file

Additional Report Settings

Report File Directory Specifies the directory for the generated report files
Specifies the filename generated by the report; move the mouse over the
Reporting Filename
'Description' label to see the variable values
Specifies a customized style sheet file used instead of the Ranorex style sheet to
C ustom XSL Filename
present the reports
Auto Save Interval
Specifies how often the report file is saved during an execution

Global Parameters
Globally specified parameters can be accessed and used by every test case within the test suite. The
KeePassTestSuite example project uses a global parameter to specify the directory path for the application under
test. You can easily connect global parameters with variables as shown in the test case 'TC _AddEntry'. In addition
you can use the global parameter to transfer values or states between test cases.

Test Case Settings


The 'General' tab of the test case's properties dialog is mainly used to setup how a broken test case impacts
other test cases within the test suite.

Name Name of the test case


Description Specifies the filename generated by the report; move the mouse over the 'Description' label to
see the variable values
Specifies a customized style sheet file used instead of the Ranorex style sheet to present the
Report Level
report
Specifies the behaviour of the test case and the test suite in case of on error

Set to 'C ontinue with iteration' if the case should not break in case of an error caused by
Error a particular data set
Behavior
Set to 'C ontinue with sibling' if the case should not break and continue with the next test
case
Set to 'Stop' in order to break the test suite run in case of an error

Page 37 of 247
Test case properties dialog

Use the context menu to change the report level or the error behavior for multiple test cases.

Specifying error behavior for multiple test cases

C opyright © 2012 Ranorex

Page 38 of 247
Lesson 5: Ranorex Recorder
The Ranorex Recorder is used to record and replay the user's keyboard and mouse actions during a manually
executed test of the user interface. In addition the Recorder can validate current states, properties like 'Text' or
'Visibility' and compare images of UI elements. The Recorder is a capture replay editor which is available both as
stand-alone tool and as an integrated editor within Ranorex Studio.

Ranorex Recorder integrated in Ranorex Ranorex Recorder as standalone tool


Studio

Within Ranorex Studio you can add a new recording in different ways.
Use the project view to add a new recording by clicking the 'Add Recording Module' button on the toolbar.

Add a recording module by clicking the


button on the toolbar

Alternatively you can also add a recording directly to a test case within the test suite editor.

Adds a new recording to an existing test case

During the next chapters you learn about the following:

Before Starting to Record


Page 39 of 247
During Recording
After Recording
Replay and Debug Actions
Recorder Variables
User C ode Actions
Additional Editing Options
Image-Based Automation

C opyright © 2012 Ranorex

Page 40 of 247
Before Starting to Record
Regardless whether you use Ranorex Recorder within Ranorex Studio or as a stand-alone tool, both the Recorder
and also the system under test have to be prepared.

Prepare to Record
Before you start recording, you need to ensure that your system under test is ready to start with the manual test
execution. In addition, consider the following points in order to avoid too much effort in cleaning up the recording
and the repository afterwards.

Do not run multiple instances of your application under test if that is not part of the test case itself
By default, mouse movements are not recorded; for this reason please also perform mouse clicks in
situations such as navigating through menus (or use Recorder Hotkeys to record mouse movements)
Think about which steps should be part of the final test
Try to keep recordings small in order to make them modular

Recorder Settings Dialog


Before running a new recording session, you can also configure Ranorex Recorder using the settings dialog. C lick
the 'Settings' button to open the settings dialog.

Settings for current recording file Default values used for every recording

Current Recording
This tab primarily contains configuration parameters for code generation specific to the current recording. All
settings on this tab page are stored within each recording.

Recording namespace:

Specifies the namespace used for the generated code.

Recording class name:

Specifies the class name used for the generated code.

Enable turbo mode for replay and generated code:

Is used to specify whether recorded delays between actions should be part of the generated code.

Generate replay reports:

Page 41 of 247
This setting is used to turn the generation of reports during replay on and off.

Use item logging by default:

Activate this setting to turn on a default logging message for each action item.

Recorder Defaults
Under this tab you can specify global default values for every newly created recording. The settings are divided
into three sections:

Recording

Record relative element coordinates: 

If checked, relative coordinates within a recognized element are recorded. Otherwise, actions will always be
invoked on the 'center' of the recognized elements.

Capture a screenshot for each step:

Specifies whether a screenshot of the current action should be made during the recording.

Highlight clicked elements:

Specifies whether objects clicked during a recording should be highlighted.

Timings for new actions


Note: Please note that the following settings only affect newly created actions, not existing actions.

Key sequence split time (ms):

Use this setting to specify the maximum time for a key sequence during recording. If a key sequence exceeds
the time set, it is split into several key sequences.

Mouse move time per action (ms):

Specifies the time in milliseconds used to move the mouse to the UI object related to the action.

Mouse related action time (ms):

Specifies the overall time in milliseconds used for a manually created mouse action. The value set for this setting
is only taken into account for manually created actions or when the time of an action cannot be determined
during recording.

Keyboard related action time (ms):

Specifies the default overall time in milliseconds used for a manually keyboard action. The value set for this
setting is only taken into account for manual created actions or when the time of an action cannot be determined
during recording.

Code Generation
Recording namespace:

Specifies the namespace used for the generated code.

Recording class name:

Specifies the class name used for the generated code.

Generate replay reports:

This setting is used to turn the generation of reports during replay on or off.

Use item logging by default:

Activate this setting to turn on a default logging message for each action item.

C opyright © 2012 Ranorex

Page 42 of 247
During Recording
C lick the 'Record' button to trigger a new recording. 

Click 'Record' to start recording

After clicking the record button you're assisted in running an application or opening a browser to navigate to a
particular URL before recording any user performed actions. Therefore it’s not necessary to record actions like
double clicking a shortcut on the system’s desktop.

New recording dialog

Note: If you select 'Run Application', 'Open a Browser' or 'Mobile Recording' the recording is not limited to the
application, browser or mobile device.

After clicking the 'Start' button, the Recorder or Ranorex Studio will be minimized. A running recording session is
indicated in the Ranorex Recorder tool bar.

Ranorex Recorder toolbar

Now perform all the actions you want to be part of the automated test. You can also pause the recording session
at any time by clicking the ‘Pause’ button.

Validation
The Ranorex Recorder provides two different types of validation during a running recording session:

Validation based on property values of a UI element


Image-based validation

Page 43 of 247
Validating States or Properties
The Ranorex Recorder tool bar can be used to validate states or properties of GUI elements during a running
recording session. C lick the 'Validate' button to pause the recording in order to start the validation.

Validation mode is active

Recording is now paused. Move your mouse pointer over a specific UI element. Wait a moment to ensure that the
highlight frame is surrounding the intended UI element indicating that it is ready to be validated. C lick on the
element to open the validation dialog.

The highlight frame specifies the element to The dialog shows the available
validate attributes for validation in a list of
checkboxes

To validate UI elements of pop-up windows like menus, use the shortcut key 'V' to turn on validation mode
without clicking the 'Validate' button. Read more about how to enable hot keys in the section Recorder Hotkeys
later on in this lesson.

Validation of menu items using shortcuts

Validating Images

In addition to validating attribute values of a UI element, it is also possible to validate images or screen regions
of an application. Simply switch to validation mode as described above and select a UI element. To validate the
element's image, open the 'Image' tab in the validation dialog.

Page 44 of 247
Validate whether a specific Listitem contains a
specified image or not

Recorder Hotkeys
Ranorex Recorder provides useful hot keys for triggering special features like validation or the recording of
simple mouse movements. When you start a new recording session, the hot key functionality is turned off. To
activate the Recorder's hot keys simply click on the 'Enable Hotkeys' checkbox or press the master hot key
'<SC ROLL>'.

The recorder's toolbar will then shows what type of shortcuts are available.

Available hot keys during a recording session

'V':

Press the hot key 'V' to turn on validation mode - especially useful for validating elements of a pop-up window
like menu items and drop-down lists.

'M':

Use the hot key 'M' to record simple mouse movements. Simply move the mouse pointer to a certain position and
press the hot key to record the mouse movement in relation to the underlying UI element.

'T':

It's easy to validate the content of a tooltip by pressing the hot key 'T' after the tooltip box appears. Ranorex
Recorder automatically captures a mouse move action in realtion to the underlying item and validates the current
content of the tooltip.

'I'

The hot key 'I' is used to turn on/off image-based recording - used for pop-up windows, menu items or drop-
down lists.
Page 45 of 247
'Roll Mouse Wheel'

Roll the mouse wheel during validation mode to change the level of UI element selection.

C opyright © 2012 Ranorex

Page 46 of 247
After Recording
After pressing the ‘Stop’ button of the Recorder’s toolbar, the recorder represents all low level actions like clicking
on a button or typing text within the action’s table.

Recorded actions listed in the recorder's actions table

By default each recorded action has an additional screenshot shown on the right. Depending on the type of
action, each row shows additional action-related information. Whereas a mouse related action provides more
information about the type of mouse action (C lick, Double-C lick, Move, etc.) or which button was used (Left,
Right, etc.) a key sequence action only stores the keystrokes made during a recording.

Recorded mouse click action

Recorded key sequence action

Additionally each action can be connected to a UI element represented by the repository view below. For each UI
element used during a recording session the recorder generates an item in the given repository.

Note: In case an item already exists in the repository or if the UI element is used twice during a recording
session the recorder reuses this element.

By default the repository is not part of the recording file and only refers to the main repository used within a
project. In comparison to the integrated Recorder, the standalone Recorder tool embeds the repository by
default. You can also unlink and refer to another file or embed the repository into the recording file. Read more
about how to do that in Lesson 6: UI Mapping with Ranorex Repository - Repository Separation.

Key sequence action (at URL textfield) refers to the


repository item 'TextURL'
Page 47 of 247
Action Cleanup
After finishing the recording, it is advisable to look at each recorded action item in detail. The  recorder offers
some editing features to clean up the sequence, for example merging key sequence actions.

Changing click location for all mouse related action


items (multiple-selection) to 'Center'

By default the recorder records the mouse click location performed by the user relative to a button or a text field.
It’s possible to turn that off in advance within the Recorder’s settings dialog. Alternatively, you can also change
the click location afterwards within the properties dialog.

Changing click location for all mouse related action


items to 'Center'

Repository Cleanup
Each item within the repository refers to one RanoreXPath expression necessary to identify the object. The
names used for the items and folders of the repository are generated automatically. It is recommended to
rename them if it's helpful. Additionally the structure of the repository is generated automatically and depends on
the internal UI hierarchy given by the application under test. To rename items of the repository simply click in the
cell or press <F2> at the selected item.

Automatically generated repository

New structured and renamed repository

Use logical folders to create additional structure, for example to group input fields, buttons or a log on form with
user name and password text boxes. Also, already existing rooted folders can be used for grouping as well. Learn
more about how to work with Ranorex repositories in Lesson 6: UI Mapping with Ranorex Repository.

C opyright © 2012 Ranorex

Page 48 of 247
Replay and Debug Actions
The playback speed of each recording can be defined individually. Use the speed factor text box to increase
replay speed by a factor value.

Replay settings within Ranorex Recorder

In order to replay all actions as fast as possible, activate 'Turbo Mode' by clicking the button on the tool bar. By
activating 'Turbo Mode', the value for speed factor is ignored. Use the repeat count text box to specify the
number of iterations.

Simply click the 'Play' button in the recording to replay all actions.

Replay recorded actions

During the execution, the progress box shown at the right lower corner gives information about the current
automation state. Press the 'Pause' key to stop replaying. 

Replay status box

If the option 'Generate replay reports' is set to true, a report is shown after the replay has finished. By default
each action item logs one message to the report.

Report after replay

Within Ranorex Studio the report is shown as a new file view whereas the standalone Recorder opens the report
viewer to show the result. Learn more about how to use Ranorex reporting in Lesson 8: Reporting. As shown in
the picture above, each log entry allows one to quickly jump to the source action item. This is helpful in quickly
debugging single actions in case of an error. Within the Recorder's actions table, you can then fix an error
causing step and quickly re-run single or selected steps using the context menu.
Page 49 of 247
Play a selected item

C opyright © 2012 Ranorex

Page 50 of 247
Recorder Variables
As described in Lesson 3: Data-Driven Testing a recording can have variables instead of static string values
generated during the recording session. In particular key sequence actions used to type in such things as log in
data into a form are commonly used action items which have to be data driven in many cases. At any position
within the actions table where you can change or set values in a cell, it is possible to have variables instead.

Variables used for key sequence actions

The variables shown in the table above are in green. All variables used within the recording can be connected to
a Ranorex data connector or to simple parameters provided by the the entire test suite or a single test case.

Creating Variables
There are different ways to create new variables for a recording. During Lesson 3: Data-Driven Testing you
learned how to create variables directly within the actions table.

Create a new variable for a key sequence action Create a new variable

Not only key sequences can use a variable. To make a click action data driven - for example selecting an icon for
password entry - you need to define a repository variable used for identification within a RanoreXPath
expression. Select the context menu item 'Make Item Variable...' to create a new repository variable in order to
have a data driven mouse click action.

Make new variable to be used within the path of the repository item

Page 51 of 247
Create a new variable for selecting the menu item

Another option is to open the variables dialog where you can add new or change existing variables already used
by the recording. Moreover, you can see which variables are 'In use', 'Not in use' or 'In use from Repository'.

Open the variables dialog in the Recorder

Variable dialog of a recording with different levels of


usage

Use the toolbar to add, remove or copy a variable from the repository. C hange the name of the variable and set
a default value by clicking in the cells of the table. Press the 'C opy Variable from Repository' button in the tool
bar to make variables defined in the given repository available for the recording. Read more about variables
specified in repositories in Lesson 3: Data-Driven Testing - Using Variables within the Repository.

C opyright © 2012 Ranorex

Page 52 of 247
User Code Actions
A user code action is used in situations where standard out-of-the-box features provided by the recorder are not
enough. Here are some examples in which a user code action could be a great convenience.

User-specific Validation
Accessing test case related data and parameters
Extended reporting

Looking at a recording file in the project's view you will see that each recording has two code items.

Recording 'AddNewEntry' has two code file


items

Note: User code actions are not available within the standalone Recorder.

Within Ranorex Studio, each recording manages two types of source code files:

Automatically generated main recording source code file


<RecordingName>.<ScriptFileExtension>
User specific source code file<RecordingName>.UserC ode.<ScriptFileExtension>

Every time you change and save a recording, the main code file 'AddVip.cs' is newly generated. Any change of
code should always be made within the recording's UserC ode.cs file.

Create User Code Actions


You can create user specific code actions by converting existing items or by adding a new 'Usercode' action item
viathe toolbar button 'Add New Action'.

Page 53 of 247
Convert an existing action item to a code action

Specify method name used for user code item

Use the context menu item 'View User Code' to


jump into the code

After the creation of a new user code action within the actions table, a new method is added to the partial class of
the recording. If you're converting an existing action item, the code generated for the main recording file is
transferred to the new user code method.

C#
view plain c opy to c lipboard print 5
namespace MyFirstTestProject   
{   
    public partial class AddNewEntry   
    {   
        /// <summary>   
        /// This method gets called right after the recording has been started.   
        /// It can be used to execute recording specific initialization code.   
        /// </summary>   
        private void Init()   
        {   
            // Your recording specific initialization code goes here.   
        }   
  
        public void ClickOnPasswordField()   
        {   
            Report.Log
(ReportLevel.Info, "Mouse", "Mouse Left Click item 'FormAdd_Entry.TabPageList.InputFields.TextPassword' a
  
            repo.FormAdd_Entry.TabPageList.InputFields.TextPassword.Click("175;9");   
        }   
  
    }    6
3 4

VB.NET
view plain c opy to c lipboard print 5
Namespace MyFirstTestProject   
    Public Partial Class AddNewEntry   
        ''' <summary>   
Page 54 of 247
        ''' This method gets called right after the recording has been started.   
        ''' It can be used to execute recording specific initialization code.   
        ''' </summary>   
        Private Sub Init()   
            ' Your recording specific initialization code goes here.   
        End Sub  
  
        Public Sub ClickOnPasswordField()   
            Report.Log
(ReportLevel.Info, "Mouse", "Mouse Left Click item 'FormAdd_Entry.TabPageList.InputFields.TextPassword' a
  
            repo.FormAdd_Entry.TabPageList.InputFields.TextPassword.Click("175;9")   
        End Sub  
  
    End Class   6
3 4

User Code Actions and Parameters


Since Version 3.3 it is possible to use parameters for user code actions. So you can pass (string) values to your
user code methods to gain more flexibility to your testing environment.

To use parameters for a new user code action, simply click the cell next to the method's cell and type in a value
to be used as a parameter (e.g. 'WordPressDemo').

User Code Action with a parameter

Of course you are also able to use more than one parameter for each action. If there are no more columns
available (maximum of three in the GUI), you can use the browse button to access the Ranorex Argument Editor.

Browse button to access the Ranorex Argument


Editor

To enhance flexibility, you can use variables instead of hardcoded values. This can be done in the normal way.

Create a new variable to be used as a parameter

You'll find an overview of existing parameters in the Ranorex Argument Editor. Here you can also name existing
parameters and add additional parameters.

Ranorex Argument Editor for handling user code


parameters
Page 55 of 247
After declaring the parameters with values or variables, you can switch to the user code method and use the
passed parameters..

C#
view plain c opy to c lipboard print

public void AddEntryWithParams
(string aTitle, string aUsername, string aPassword, string aURL)   
{   
    MyFirstTestProjectRepository MyRepo = MyFirstTestProjectRepository.Instance;      
       
    // Set text fields   
    MyRepo.AddEntry.TabSheetAddEntry.Title.TextValue = aTitle;   
    MyRepo.AddEntry.TabSheetAddEntry.UserName.TextValue = aUsername;   
    MyRepo.AddEntry.TabSheetAddEntry.Password.TextValue = aPassword;   
    MyRepo.AddEntry.TabSheetAddEntry.Repeat.TextValue = aPassword;   
    MyRepo.AddEntry.TabSheetAddEntry.URL.TextValue = aURL;   
}  

VB.NET
view plain c opy to c lipboard print

Public Sub AddEntryWithParams
(aTitle As String, aUsername As String, aPassword As String, aURL As String)   
    MyFirstTestProjectRepository MyRepo = MyFirstTestProjectRepository.Instance   
       
    ' Set text fields   
    MyRepo.AddEntry.TabSheetAddEntry.Title.TextValue = aTitle   
    MyRepo.AddEntry.TabSheetAddEntry.UserName.TextValue = aUsername   
    MyRepo.AddEntry.TabSheetAddEntry.Password.TextValue = aPassword   
    MyRepo.AddEntry.TabSheetAddEntry.Repeat.TextValue = aPassword   
    MyRepo.AddEntry.TabSheetAddEntry.URL.TextValue = aURL   
End Sub  

Additionally to creating method calls in Ranorex Recorder you are able to define your methods in code and just
select the intended method in the Recorder Table. Here you are also able to choose overridden methods.

Chose one of the overridden method calls

Ranorex Argument Editor with arguments and


variable binding from overridden method

Conditions in Code
Another reason for writing user code is to read text values from UI elements like text boxes and to reuse them
for conditional automation steps.
Page 56 of 247
Note: Only create small and easy to maintain user code actions for a recording. If an implemented method is to
also be available for other test cases, create a code module (see Lesson7: C ode Modules) instead.

Within the 'DeleteEntry' recording that was created in Lesson 3: Data-Driven Testing, there are three simple
actions in deleting the selected entry (selecting the item, opening the context menu and choosing the context
menu item). As you can see it is meaningful to only delete a entry if it is selected. Therefore a condition in code
could be useful.

As a first step, open the 'DeleteEntry' recording and select the last two items as only they should be executed if
the entry is selected. C lick on the 'Merge Items to User C ode Item' menu item in the context menu.

Context menu item to 'Merge Items to User Code


Item'

After doing this, these two actions are merged into one user code action. Give this method a meaningful name
(e.g. 'DeleteItemIfFocused'). Switch into the code view by clicking on the context menu item 'View User C ode'.
Now change the converted code so it is only executed if the cell is focused on.

C#
view plain c opy to c lipboard print 5
public void DeleteItemIfFocused()   
{   
    if (repo.MainForm.Entry.HasFocus) {   
           
        Report.Log
(ReportLevel.Info, "Mouse", "Mouse Right Click item 'MainForm.Entry' at 127;10.", repo.MainForm.EntryInfo
  
        repo.MainForm.Entry.Click(System.Windows.Forms.MouseButtons.Right, "127;10");   
           
        Report.Log
(ReportLevel.Info, "Mouse", "Mouse Left Click item 'KeePass.DeleteEntry' at 168;14.", repo.KeePass.Delete
  
        repo.KeePass.DeleteEntry.Click("168;14");   
    }   
        6
3 4

VB.NET
view plain c opy to c lipboard print 5
Public Sub DeleteItemIfFocused()   
    If repo.MainForm.Entry.HasFocus Then  
  
        Report.Log
(ReportLevel.Info, "Mouse", "Mouse Right Click item 'MainForm.Entry' at 127;10.", repo.MainForm.EntryInfo
  
        repo.MainForm.Entry.Click(System.Windows.Forms.MouseButtons.Right, "127;10")   
  
        Report.Log
(ReportLevel.Info, "Mouse", "Mouse Left Click item 'KeePass.DeleteEntry' at 168;14.", repo.KeePass.Delete
  
        repo.KeePass.DeleteEntry.Click("168;14")   
    End If  
   6
3 4

C opyright © 2012 Ranorex


Page 57 of 247
Page 58 of 247
Additional Editing Options
As you have learned in the previous lesson, the Recorder is usually used to record user actions. After making a recording, it might be necessary to edit the
recorded data, for example to merge split key sequences or to delete single actions recorded by mistake. You can also add new actions like a new validation step
which was not considered during the recording. In the following section you'll learn about:

Adding New Actions
Recorder Variables
Splitting Recordings

Adding New Actions


There are two ways to add actions to the actions table manually. One way starts with specifying the action as a first step and continues with assigning a repository
item (in most of the cases). The second method starts with dragging and dropping of a repository item directly into the actions table including the specification of
the action itself.

Using the 'Add New Action'-button


To add a new action item, open the \RXEmph{Add New Action} drop-down menu as shown below:

Add a new action item to the actions table

By selecting one of the items a new action is added after the current selection within the actions table.

New mouse move action added

Depending on the type of action item, you may be able to configure each action individually. Before doing that, you should first assign a repository item to this
action - this might affect the available options for the specified action. You should click the small button framed in red in the graphic above and chose the
Repository item related to the newly created action. The items listed within the 'Select Repository Item' dialog are the same as within the recording's repository.
You can use the 'Search' text box to filter the elements. You can read more about how to use repository search and how to add new UI elements in Lesson 6: UI
Mapping with Ranorex Repository - Searching for Elements. C onfirm your selection by clicking OK.

Page 59 of 247
Select a repository item to be used by the action

Alternatively it is possible to assign the repository item to the action by dragging and dropping a repository item directly onto the newly created action in the
column 'Repository Item'.

Assign a repository item to the action via drag and


drop

To modify the newly created action, use the drop down menus available within the cell, for example you can change the action from 'C lick' to 'Move'.

Available sub-actions for mouse action

Drag and drop repository item to initiate adding a new action


Alternatively to the method presented above, you can also drag and drop repository items into a new line in the actions table of a recording as shown in following
graphic.

Use drag and drop to create a new action for a


specific repository item

You are asked to specify the type of action after dropping the element into the actions table. For more information about the available actions, see below.

Types of Action Items

Page 60 of 247
Mouse Adds a new mouse action item at the current position

Mouse Wheel Adds a new mouse wheel action item

Touch Event Adds a new touch event action item at the current position

Key Shortcut
Adds a new key shortcut action item (e.g. {F1}, {ENTER})

Key Sequence Adds a new key sequence action item (e.g. "Hello")

Mobile Key Press


Adds a new mobile key press action (e.g. \{BAC K\}, \{MENU\})

Validation Adds a new validation action item

Invoke Action Adds a new invoke action item (e.g. call method 'Select' for a UI element of type list item)

Get Value Adds a new get value action item (e.g. get 'Text' for a UI element of type button)

Set Value Adds a new set value action to set an attribute value (e.g. 'Text' for a UI element of type text)

Open Browser Opens a browser and navigates to the given URL

Run Application Runs an application at the given directory and file path

Run Mobile App Runs an application on a mobile device

C lose Application C loses an application or web site containing the given repository item

Wait For Not Exists Waits for the disappearance of the given repository item
Note: This action can be used for any type of UI element

Adds a new report action item


Report
Note: In addition to the standard report levels, you can define custom report levels by changing the level from "Info" to "C ustom"

Separator Inserts a separation line on the currently selected position in the actions table

Delay Adds a new delay action item

User C ode Adds a new user code action item which is used, for example to implement a user specific validation in code

Note: Keep in mind that most types of action can handle module variables.

Note: Next to the parameters as described in the next paragraphs there might be additional options for each action which can be accessed in the properties pane.
You can open this pane by clicking the context menu item 'Properties' on any action item.

Mouse
This mouse action can be used for 'Up', 'Down', 'C lick', 'Double-C lick' and 'Move'-actions. This action is typically used for button clicks so a repository item
assignment is required.

Mousewheel
This mousewheel action can be specified as 'Vertical' or 'Horizontal' direction. You are also able to specify a wheel-delta, which is 120 by default.

Touch Event
This touch event can be used different kinds of touch events on mobile devices. For more information please have a look at Android Testing - Record your Android
Test.

Key Shortcut
This action can be used for executing key shortcut actions. Aside from the shortcut itself, it is possible to specify the key codes 'Press', 'Up' and 'Down'. For this
action, a repository item assignment is needed.

Key Sequence
This action makes it possible to execute or to simulate a key sequence on a specified repository item. This action is typically recorded in a form filling scenario (e.g.
username field in login process). For this action a repository item assignment is required.

Mobile Key Press


This action can be used for pressing mobile keys like {BAC K} and {MENU}. For more detailled information please have a look at Android Testing - Record your
Android Test.

Validation
The validation action is typically used for validating states, text or images of specific repository items. Every validation action leads to a specific entry in the report
file and, depending on the type of validation and the validated element, there may be different validation results (success, failure). After assigning a repository
item, you are able to choose one of the following validation-types:

Exists: The validation checks for the existence of the repository item and expects an existing item.

Example: A user can validate whether a button exists with a resulting success if the button actually exists.

NotExists:The validation checks for the existence of the repository item and expects the item not to exist.

Example: A user can validate whether an error dialog does not exist with a resulting success if the dialog does not exist.

AttributeEqual: This validation checks whether an attribute (column 'Match Name') is equal to a specific value (column 'Match Value'). The matching attributes
depend on the assigned repository item and therefore an assignment of a repository item is assumed. For example a Winforms button may be validated on the
'Text', on the 'Valid' state, on the 'Pressed' state and also on 'AccessibleName', 'AccessibleValue' etc.. The matching value can either be a constant, a self-defined
value or a module variable.

Example: A user can validate whether a button has the text 'OK' with a success result if the button text is 'OK'.

AttributeRegEx: This validation is for matching a 'match value' (self-defined match value or the content of a module variable) against a specific attribute (column
'Match Name') using a regular expression. Because the attribute itself (column 'Match Value') depends on the assigned repository item, assignment of a repository
item is recommended prior to choosing a match value. If you plan to use a variable within this type of validation, you can easily implement your regular expression
in the value of that variable.
Page 61 of 247
Example: One can validate whether the title of the KeePass application ends with the text 'KeePass Password Safe' and could therefore use the 'Match Name'
containing the regular expression '.KeePass Password Safe'. The validation would lead to success if the attribute (column 'Match Name') has any character (this is
defined as a . in the regular expression) followed by the constant 'KeePass Password Safe'. For more information about Regular Expressions see RanoreXPath -
RanoreXPath with Regular Expressions.

AttributeContains: This validation checks whether a specific attribute (column 'Match Name') of a specific repository item contains a 'match value'. The match
value can either be a user-defined constant value or it can also be the content of a module variable. As above this validation assumes the assignment of a
repository item.

Example: A user can validate whether the title of the KeePass application contains the constant value 'kdbx', which is the file extension of the database used by
KeePass. The match name would thus be set to 'Title' and the match value would be set to 'kdbx'. As a result the validation would succeed if the title actually
contains the constant 'kdbx'.

AttributeNotContains: This validation can be thought of as the opposite of 'AttributeC ontains'. It checks whether an attribute (column 'Match Value') does not
contain a 'match value'.

Example: One can validate whether the content of a specific cell (URL) in KeePass does not contain the constant value 'http://'. 'Match Name' would therefore be set
to 'Text' and 'Match Value' would be set to 'http://'. This validation would lead to a positive result if the URL does not contain the constant value 'http://'.

ContainsImage: This validation checks whether the assigned repository item contains a specified screenshot. This screenshot can be easily created within the 'Edit
Image Validation' which can be accessed via a button in the 'Screenshot' column. For more information about image-based validation please have a look at the
section entitled Image-Based Automation later in this chapter.

Example: It's possible to validate whether the user-defined list of icons (for a KeePass entry) contains a specific icon. This could be done using image-based
validation. The repository item would therefore hold the list of icons and the screenshot would be a picture of the specified icon. The validation would lead to a
result if the list contains the specified icon.

CompareImage: This validation checks whether a specified repository item is equal to a specific screenshot. This screenshot can be easily created within the 'Edit
Image Validation' which can be accessed via a button in the 'Screenshot' column. For more information about image-based validation please see Image-Based
Automation later in this chapter.

Example: One can validate whether the toolbar of the KeePass application contains the intended icons and so can compare the repository item with a screenshot of
the toolbar in initial state. This validation would lead to success if the toolbar looks exactly the same as the screenshot.

Invoke Action
This action can be used for invoking actions on the specified repository item. For example a Winforms button provides functionality for 'Ensuring Visibility',
'Focusing' and 'Pressing'. More important, this action can be used to easily select items in lists and drop-downs. No mouse movement and click is simulated but
nevertheless the item itself is selected. This is a more powerful and smarter action than simulating the selection via mouse actions. Invoking a select action on a
specific item also works if the item itself is not visible by default because there are too many elements in the list and there would therefore be a need to work with
a scroll bar.

User-defined actions: In addition to providing actions delivered by default, you can also make use of user-defined (see Invoking User-Defined Actions).

Get Value
As the action name indicates, this method can be used for getting values from repository items. Depending on the assigned repository item, the available attributes
can be different. The value obtained can be assigned to a module variable. Depending on the available adapters for the assigned repository item, the attributes are
divided into several sections.

Submenu for Get-Value action

User-defined methods and attributes: In addition, it is also possible to call user-defined methods defined in your system under test. As is described in the next
section (see Invoking-User Defined Actions), a simple application could have a public function that returns a string value holding the text of a protected text field. If
the application is running during the creation of the GetValue-Action, there is a submenu for 'Dynamic' methods. Public attributes can also be accessed and
returned through the 'Dynamic' submenu.
Note: To get access to the dynamic methods and attributes, the repository item has to be available. This can be verified by highlighting the specific element by
right clicking the element in repository and choosing 'Highlight Element' from the context menu.

Reuse values from the GUI in other modules: Using a Get Value action allows one to store an attribute value of a UI element to a module variable. Doing so
makes the value available within one module.

Text value of a button stored in a variable

To make the value stored in the module variable available in other modules, it's necessary to bind the variable to a parameter it can also be bound to other
variables in other modules.

Page 62 of 247
Two variable are bound to one parameter for
accessing a variable value from one module to
another

Set Value
As the action name indicates, this method can be used for setting the values of repository items. Depending on the assigned repository item, the available
attributes might be different. Depending on the available adapters for the assigned repository item, the attributes can be divided into several sections as seen
below.

Submenu for Set Value Action

User-defined attributes: In addition, it is also possible to set user-defined attributes. If the application is running during the creation of the Set Value action then
there is a submenu for 'Dynamic' methods holding dynamic attributes.
Note: To get access to the dynamic methods and attributes, the repository item has to be available. This can be verified by highlighting the specific element by
right clicking the element in repository and choosing 'Highlight Element' from the context menu.

Open Browser
This action can be used for opening a browser. For preperation you are able to use the parameter 'URL' for directly opening a website. The parameter browser can
be used for choosing a browser (e.g. 'IE', 'C hrome', 'Safari' or 'Firefox').

Note: You can use a 'module variable' inside the column 'Browser' which can be used for cross-browser testing. For an extensive description including an example
see C ross-Browser Test Automation with Ranorex.

Additionally there is a parameter 'Maximized'. When this parameter is set to 'false', the URL is opened in the default browser window size which can nevertheless be
in maximized state. With the maximized-parameter set to true, the browser will be opened in maximized window state.

Run Application
This action can be used to run an application which filename can be specified in the column 'File Name'. You can also pass some arguments (column 'Arguments')
and define, whether the application should be started in maximized window state (column 'Maximized', see explanation for open browser action to find out more
about this parameter).

Run Mobile App


When using this action you can specify a 'Device' and an 'App'. For more information see Android Testing - Record your Android Test.

Close Application
This action can be used for closing applications and web sites. If the 'C lose Method' is set to 'C loseWindow', the application is attempted to be closed. If the
parameter 'Grace Period' is set to a value greater than 0 ms, the process will be killed after the 'Grace Period' if the closing of the application failed. If 'C lose
Method' is set to 'KillProcess' the application's process is killed immediately and the grace period has no influence.

Wait For Not Exists


You can use the 'Wait for not exists' action to wait until the assigned repository item does not exist anymore. You can also specify a 'Timeout'.

Report
The Report action is typically used for providing information related to the test report.

After assigning a repository item, you are able to choose one of the following action types:

Log: This action adds a line of text holding a given value to the test report.
Example: One could report the current value of a variable or UI element.

Screenshot: This action adds a screenshot of a specific repository item and some user-defined text to the test report.

Example: One could report a screenshot to make the report file clarify the current state of the system under test in the report file.

Snapshot: This action adds a snapshot file of a specific repository item and some user-defined text to the test report. The snapshot file can be opened directly
from the report file.

Example: One could report a snapshot file of the application under test if an automation problem occurs in order to analyze this automation problem.

In addition to the specification of the action type you are also able to deliver a 'Message' and to specify a 'Report Level'. For more information about the 'Report
Level' see Lesson 8: Reporting.

Separator
A separator can be used to visually separate recordings into smaller sections to get a clearer view of thematically related actions. You can specify a 'Header Text'
to name or describe the following group of actions.

Delay
A delay action can be used to pause test automation execution for a specific time (column 'Duration').

User Code
User code actions can be used to access some small units of code directly within the recorder. User code actions are described extensively in User C ode Actions.

Invoking User-Defined Actions


Sometimes it might be useful to access internal, user-defined functionality from your system under test. You could use the recorder action 'Invoke Action' which
Page 63 of 247
also allows parameters. For example a simple Winforms application 'Invoke-Example' written in Visual Studio (C #) provides a button which automatically sets a
constant text to a protected text field.

Example (in initial state) with public functionality


which will be invoked

C#
view plain c opy to c lipboard print

public void MyInvokedAction(string MyMessage)   
{    
    edProtectedText.Text = MyMessage;   
}    
  
private void btSetValue_Click(object sender, EventArgs e)   
{   
    edProtectedText.Text = "This text was set from GUI";   
}  

The protected text can only be set by clicking the button. The application then sets the text field to a constant value.

Example after clicking the button without invoking


functionality

Ranorex provides the functionality for accessing methods that are classified as public directly within the actions table. The public method 'MyInvokedAction' can
easily be called including a user-defined parameter. When adding the new action it is recommended to keep the application ('InvokeExample') open because
accessible functionality is determined dynamically.

Page 64 of 247
Submenus for available invoke actions

Even parameters can be easily set in the Ranorex Recorder table.

Setting a paremeter for an invoked action

You can also access an attribute editor from a browse button in the last argument column to get an overview of available parameters.

Browsing available arguments

After invoking this method, the text field is set to a text that is delivered as a parameter in Ranorex.

Example after invoking a method from Ranorex

Continue On Fail and Disable


Each action item listed in the table can be disabled or set to \RXEmph{C ontinue On Fail}. Set an action item to \RXEmph{C ontinue On Fail} if, in cases of error, the
replay should not stop at that position. You can set both options via the context menu or the property grid. Items set to continue on fail are in italics in the actions
table whereas disabled action items appear in gray.

Disabled action in gray font color - Continue-On-Fail action using italic font style

Note: In case of an error the particular action logs a warning to the report.

Splitting of Recordings
The more recorded actions you have after finishing a new recording, the less clear each single action becomes. As was already mentioned in Lesson 2: Ranorex
Modules - Test Actions, identifying reusable steps within a newly created recording is recommended. Use the context menu item 'Move to New Recording Module' to
create a new recording module.

Creates a new Recording from the selected items

Use the test suite editor as described in Lesson 2 and Lesson 4 to combine multiple recording modules into one test case.

Page 65 of 247
Change Repository of Recording Module
By default each newly created recording refers to the main repository file. To create a new repository or to refer to another repository simply open the drop-down
menu from the repositories toolbar as shown below.

Change referring repository

Select 'Open From Disk' if you want to open and refer to a repository which is currently not part of your Ranorex Studio projects. If you want to use a repository
exclusively for a single recording, simply embed it into the recording file. In this case all the repository items are saved to the recording file. C reating a new
repository for your recording automatically adds a new repository file to the current project.

C opyright © 2012 Ranorex

Page 66 of 247
Image-Based Automation
In some situations, required information for automation is not available as text but only as a graphic. Therefore
Ranorex provides image-based automation to bypass the lack of availability

Sometimes you need to automate a click action based on image information. For this reason, Ranorex Recorder
provides an optional way to capture image related mouse actions. To activate image-based recording, simply
check the 'Image based' checkbox in the Recorder's toolbar during a recording session.

'Image based' recording activated

Now move the mouse pointer over a certain GUI element. Ranorex highlights the last accessible UI element and
also highlights a recognized image within the GUI element. To turn off image-based recording, uncheck the
checkbox or press the shortcut key 'I'.

Note: Hot key functionality has to be activated by first using the master hot key 'SC ROLL'. Read more about hot
key useage in the current lesson in the section entitled Recorder Hotkeys.

Introductive Example
Within KeePass application, there is a way to include some user specific icons for password entries (e.g. someone
could use the WordPress logo for his WordPress password entry). For automation of a click on a custom icon, it
might be necessary to use image-based automation because the order and in addition the index of the icon can
change because icons with a lesser index can be deleted.

KeePass Icon Picker dialog containing two custom


icons

To prepare image-based automation for a click on a custom icon, activate image-based recording. Move the
mouse pointer to the listview for custom icons in KeePass and wait until the whole listview frame is highlighted.
Execute a mouse click on the listview (take care to not click on a custom icon). The click has to be made on the
whole list in contrast to a click on an (icon) element because this click defines on which element the prospective
image has to searched.
After stopping the recording session, the actions table contains an image-based validation action which is
indicated by the 'Image' keyword or the 'Screenshot' keyword if the cell is focused on. In addition, the related
repository item stores a snapshot at the time of recording. Generally, the repository item saves an image to
specify where to search for the image region which is specified by the image-based mouse action in the
Page 67 of 247
recorder's actions table.

The Ranorex Studio image editor

In order to automate the image-based click on the custom icon, you have to tell Ranorex which image (or part of
the image in this case) you want to find and click within the graphic of the listview. Open the image editor by
clicking on the button in the location cell (see graphic above). In this dialog use the 'Select image find region'
method to define the user-defined icon which should be clicked. Additionally use the 'Select click location'
functionality to tell Ranorex at which position the mouse click should be executed. This features will be described
in more detail later on in section entitled Image Editor.

'Select image find region' and 'Select click location'


in Ranorex Image Editor

In this example, Ranorex has been automated to search for the custom WordPress logo within the entire listview
of all available custom icons. If found, this icon is clicked regardless of the position of the icon. Again, Ranorex is
not searching for any index or any list item at a specific position but for a specific graphic within a region (which
is a screenshot of the listview in this case). To check it, delete the KeePass icon with the index 0 and execute the
recording again. The WordPress icon will be found and will be clicked although the position and the index changed
in comparison to the time of recording.
To alter the settings of an image-based automation action, open the property group 'Image-Based Location'
within property grid.

Image-based Location Settings  


Use the property group to set advanced image search options like 'C lipping' or 'Best Match'
Advanced
Options If 'Best Match' is set to true, the result position with the highest similarity is used for
validation. If is set to false, the first available result position will be used for the validation.
The first is more accurate and the second is faster.
Preprocessing Defines preprocessing steps that can be performed on an image before search (e.g.
GrayScale or DownSize)
Screenshot
Name Specifies the name of the screenshot to search.

Selection
Defines the image selection region and what to search for.
Rectangle
Specifies the minimum similarity that the image region to search for needs to have in
Similarity
common with the image in order to be considered a match.

To set up the default values for image-based recording, open the 'Settings' dialog and the 'Imaging' tab.

Page 68 of 247
Settings dialog for image-based recording

Image Editor
Use the context menu item 'Edit Location...' to open the image editor and to change the click location options.

The editor provides a more detailed view of the captured image information. In addition, it offers some useful
features for changing the image rectangle to be searched for.

Click location dialog to change the settings of image-


based mouse actions

Image Editor Functionality  


Image Based Specifies whether the click is based on image information or not

Select Image Find Region Specifies the region to search within the image

Select C lick Location Defines the click position in relation to the searched region

Autoselect Image Find Region Helps to specify the search region within the image

Zoom Out
Zooms out

Zoom 100% Switches to 1:1 view

Zoom In Zooms in

C apture New Screenshot C aptures a new screenshot from the related repository item

Use the drop-down combo boxes to specify whether a mouse action should be performed relative to the image
region found or not.

Page 69 of 247
Set relative or absolute mouse action location

If the captured screenshot has to be updated, click the 'C apture New Screenshot' toolbar button. Every newly
created screenshot is also automatically added to the image list of the related repository item so it's available for
other image-based validation or automation actions.

Add a new image or select an


existing image to specify the
location/graphic to search

C opyright © 2012 Ranorex

Page 70 of 247
Lesson 6: UI Mapping with Ranorex Repository
The Ranorex Element Repository is used to separate identification information (RanoreXPath) from Ranorex test
automation modules. For test maintenance, it is recommended that you also use Ranorex repositories within code
modules to reduce the effort in adaptation necessary when the UI under test changes. In the following lesson
you'll learn about:

Adapting an Existing Repository


Adding Repository Items
Waiting for UI Elements - Repository Timeouts
Editing RanoreXPath
Repository Separation
Repository Settings Dialog
Repository Items Properties

C opyright © 2012 Ranorex

Page 71 of 247
Adapting an Existing Repository
During lessons one through three you created a repository by recording a manual test scenario. For each UI
element used during the recording, a new item was created within the repository. By default a new Ranorex
Studio project contains one repository file (*.rxrep) which can be used by multiple recording or code modules.

File view of a repository

Integrated repository view within the Recorder

You can access and edit the repository within a recording or by double clicking the file
('MyFirstTestProjectRepository.rxrep') in the projects view as shown in the figures above.

Renaming Repository Items


Each UI element within the repository can have a logical user-defined name. The more logical names you use the
easier it is to understand test automation code and report files. In order to rename an item in the repository, first
select it and then click the item to enter edit mode. Optionally you can use the keyboard shortcut <F2> to edit the
names.

Renaming of repository items

Creating Logical Folders


The more objects you have in a repository the more structured and organized it should be. For this reason you
can structure and group UI elements which logically belong together. Add a new 'Simple Folder' using the drop-
down button in the repository toolbar.
Page 72 of 247
Adding a 'Simple Folder' to the repository

Repository using two logical folders to group input fields and buttons

Repository Structure - Types of Elements


A repository can have the following types of items:

Ranorex repository structure

Application Folder #1 Represents a top level application, a dialog or a context menu

Rooted Folder #2 C ontains GUI elements having the same parent or RanoreXPath substring

Simple Folder #3
Used to group items

Represents a Ranorex adapter (Button, ListItem, TextBox, C omboBox, etc.)


Adapter Item #4

Use the 'Add New Item' button in the toolbar to add new items manually.

Searching For Elements


Use the 'Search' text box to find elements in the repository. Specify where to search for the given text value
using the drop-down menu.

Specify whether to search in 'Names',


'Paths' or to 'Search All' elements

Page 73 of 247
Search result for text 'button' used in names and
paths

Repository Cleanup
The repository's 'C leanup' button is used to search for currently unused items and then to delete items which are
not used by a recording or code module. C onsidering the situation that a user clicked unintentionally on some
desktop icons during the recording, this icons would have been added to his/her repository as well. Another
situation for the need for a cleanup would be that some UI elements which are still in the repository are not part
of the software under test anymore. In order to keep your repository as tidy as possible, use the 'C leanup'
functionality from time to time to avoid disorder in repository items.

Used and unused repository items

After clicking the 'Cleanup' button a dialog shows which elements


of the repository are currently not in use by any of recording or
code modules within the project

Select items to delete them from the repository.


Page 74 of 247
Find Repository References
In Lesson 7: C ode Modules you will learn about how to use repository items in code modules. Before you modify
an existing repository item (e.g. the item's name or the item's RanoreXPath), it might be necessary to check in
which code files the item is used. Use the context menu item 'Find All C ode References' to list all code files using
a certain repository item. You can decide to either search in all the code files or only in the user code files.

Search for references of repository item KeePass

Search result - simply double-click a result item to


open the code file

C opyright © 2012 Ranorex

Page 75 of 247
Adding Repository Items
In this section you will find several ways to add items to your repository without using the recording functionality.
In addition, you'll learn about how you can manually add actions (clicking, typing, etc.) to the recorder and
connect these actions to repository items to specify on which UI element these actions should be executed. As an
example, a new recording module 'FindEntry' will be created which opens the KeePass search form and searches
for the 'WordPressDemo' from Lesson 3: Data-Driven Testing.

You can also add new items to your repository using the Ranorex Spy tool. The following section describes how to
add the 'Find' button which was not clicked during the recording session in order to automate a click on the button
later on.

First click the 'View Spy' button within the Ranorex Studio toolbar to open Ranorex Spy.

Open Ranorex Spy to track and add items to the


repository

Next track the 'Find' button in KeePass using the 'Track' button in Ranorex Spy. The identification is indicated with
the highlighted frame around the button.

Track and identify the 'Find' button with Ranorex Spy

As a third step, add the button to the repository as shown in following figure.

Page 76 of 247
Add the item to the currently open repository

Note: Alternatively you could drag and drop the item from Ranorex Spy directly into the repository from Ranorex
Studio.

Newly created item in the repository

Note: It's also possible to track a UI elements directly from the repository using the Track button.

Track directly from repository

Now the 'Find' button is part of the repository and is ready to be used by code or recording modules. C reate a
new recording module in order to handle the 'Search' scenario. Use the 'Add New Action' drop-down button in the
toolbar of the Ranorex Recorder and add a new 'Mouse' action. There is more than one way to connect the
repository item to this action:

Drag and drop the item from the repository directly into the recording grid or

C lick on the 'browse repository button' in the recording grid (column for repository item)

Alternatively you could also drag and drop a repository item into the recording grid and create a new action this
way (you will be asked which type of action you want to create when dropping the item into the grid).

Page 77 of 247
Context menu to choose one
action when creating a new
recording action directly using
drag and drop

A new recording module was already created containing a single action for clicking on the 'Find' button in
KeePass. This recording module should be able to simulate entering text into the search form and clicking on the
'OK' button to start the search. We still need more elements in our repository and some more actions in our
recording table. Please carry out the following steps, which are quite similiar to the steps already done in this
seaction.

Open the Ranorex Spy tool (if not already opened)


Track the \RXEmph(Find What) text field in KeePass using the 'Track' button in Ranorex Spy
Add the tracked text field to the repository (either with the context menu or with drag and drop)
Rename this repository item to something meaningful name (e.g. FindText)
Add a new action ('Mouse') to the recording in Ranorex Studio
C onnect this action to the repository item 'FindText'
Add a new action (Key Sequence) to the recording
C hange the value in the column 'Sequence' to a text phrase that you want to search for (e.g.
WordPressDemo)
C onnect this action to the repository item 'FindText'
Open the Ranorex Spy tool (if not already opened)
Track the 'Find' button from KeePass Search form using the 'Track' button in Ranorex Spy
Add the tracked button to the repository (choosing one of the already mentioned methods)
Add a new action (Mouse) to the recording in Ranorex Studio
C onnect this action to the repository item 'Button Find'

Note: This long list of steps shows the manually method of creating a recording. Of course these steps could be
also done as a normal recording without worrying about on the assigning of repository items.

You can easily execute a single action and multiple actions within the recorder by using the context menu item
'Play Selected Item/s' or 'Play From Here'.

Execute the single action to simulate a key


sequence on the edit field 'FindText'

Now your manually created recording consists of four actions including opening the form, clicking on the text
field, entering a key sequence and finally clicking on the 'Find' button. This simple recording can now easily be
embedded in your test case and can be made use of in any (suitable) position.

Note: Is is also possible to add a recording module two ore more times to a test case. See the following example
for more details.

Example of a More Advanced Test Case


Page 78 of 247
Within this test case it may be a good idea to combine the 'FindEntry' module with the 'Validate' module. The test
case structure in following figure would enlarge the current example to a more complex combination of modules:

Example of an advanced test case using different


code modules multiple times

To explain the test case it should be mentioned that after the setup region ('StartSUT' and 'Login') this test case
tries to 'find' a value (WordPressDemo) and to 'validate' the results. If KeePass is started with an empty
database, this validation will intentionally fail. After adding the entry ('AddNewEntry') the second instance of the
'Find' module with the subsequent 'Validate' module would succeed if the previous adding action succeeded. The
ongoing test case continues with the deletion of the item and tries to 'find' and to 'validate' again, which now
intentionally fails again. The final teardown region containing the 'Save' and the 'C loseSUT' module are executed
anyway.
Note: To prevent the recorder from stopping the run on failing the validation (intentional) please have a look at
Lesson 5: Ranorex Recorder - C ontinue On Fail and Disable and enable continuing on fail.

One Repository Item for Multiple Elements


Repository items can be assigned to more than one RanoreXPath expressions reflecting a single UI element. You
can create a repository item using a RanoreXPath which also delivers multiple UI elements. This might be very
helpful, for example, if you want to validate the visibility of any element among a great number of checkboxes on
a configuration form. This is mainly used by code modules if you do not want to have a list of hundreds of
repository items having a single checkbox each.

Use the Ranorex Spy to prepare a RanoreXPath for a multiple result and add it to the repository as described in
the previous section.

RanoreXPath delivering multiple results (All buttons


from the toolbar in KeePass)

Repository items delivering a list of elements are mainly used in code modules as described in the chapter C ode
Examples.

C opyright © 2012 Ranorex

Page 79 of 247
Waiting for UI Elements - Repository Timeouts
As was already mentioned, KeePass is not only able to work with local databases but also with databases stored
on a FTP server.

KeePass application opening a new satabase from a


URL

Depending on the speed of the internet connection and on the size of the database, the action of loading a
database from a FTP server can take up to 10 seconds. After the download has finished, the log in dialog
appears. To handle a scenario like that in Ranorex Recorder (or in the repository), every repository item has its
own value for a specific timeout. Use the context menu item 'Properties' to open the properties for the application
folder for the 'Log In' dialog.

Open properties of 'LoginWindow' application folder

In order to see what happens when the timeout value does not match the situation, set the dialog's search
timeout to 10 milliseconds in order to force an error when executing the test case again. Even without loading the
database from the external data store (e.g. FTP server) it takes some time to open the file and to bring up the
dialog. A timeout of 10 milliseconds is not enough and the 'LogIn' recording module fails.

Page 80 of 247
Test case execution failed - 'LoginWindow' was not
found within the specified timeout of 10ms

Note: In order to keep your repository suitable, reset the search timeout value for the login dialog to 30 seconds.

Waiting for a Particular UI Element State - Event Handling


You can also use the timeout approach to wait for text states such as dynamically changing text values. KeePass
provides the functionality to copy a username or a password to the clipboard in a time limited manner (12
seconds by default). During that time, the status text in the application changes indicating that confidential
information is kept in the clipboard. After 12 seconds the clipboard is cleared of the information; this is indicated
by the status text 'Ready'. The timeout value from the repository items can also be used to wait for a specific
state or property of any item (e.g. text changes to 'Ready').
To demonstrate the functionality of waiting for a particular UI element state, create a new test case (e.g.
'C lipBoardTestC ase') containing the recording modules 'StartSUT', 'Login' as well as 'Save' and 'C loseSUT'.
Between those two blocks insert a new recording module 'ValidateC lipBoard'.

Insert a new recording module after the 'LogIn'


recording

After confirming that KeePass is in a suitable state (opened, logged in, containing one data set) use the record
button from Ranorex Studio (choose 'Global Recording' and complete the following steps)

C lick the 'Validate' button from Ranorex Recorder window


Validate the status text 'Ready' after the appearance of the highlighting frame
C onfirm the 'Validation' dialog
C lick on any item in KeePass
Open the context menu and choose 'C opy Password'
C lick on the 'Stop' button in Ranorex Recorder window

Because until now there was no need to access the status text, there is no repository item holding this UI
element. The validation action was accompanied with the creation of a repository item pointing to the status text
which is identified by the text value 'Ready'. After recording these simple actions, change the order in the
recording table and move the validate action (#1) to the last position (#5).

Note: You can easily rearrange the order of recording actions by dragging and dropping them in the recording
table.

C opyright © 2012 Ranorex

Page 81 of 247
Editing RanoreXPath
The RanoreXPath is used for identifying objects and elements on the screen. Each repository item refers to a
RanoreXPath used to identify the corresponding UI element.

In order to reduce work in maintaining path expressions, repository items like buttons, text fields and list items
are automatically grouped within application folders holding the base path for each child item.

RanoreXPath separation

Press <ENTER> to change the RanoreXPath expression of an item using the edit mode or open the Path Editor
using the context menu.
By pressing the 'Edit' button, you can change the RanoreXPath using Ranorex Spy.

Context menu item for editing the RanoreXPath

Path Editor to to change attributes used for


identification

Use the path editor to select alternative attributes or to combine multiple attributes for unique UI element
identification. Additionally, here you can create variables to be used instead of static string values for data driven
identification (for more information see Lesson 3: Data-Driven Testing - Using Variables within the Repository).
Learn more about how to work with the path editor in Lesson 10: RanoreXPath Editor.
After changing the identification attribute from 'AccessibleName' to 'Text' you can quickly verify the new
RanoreXPath using 'Highlight element' as shown below.

Page 82 of 247
Highlight the modified element to check the
modified path

Save button as highlighted element

C opyright © 2012 Ranorex

Page 83 of 247
Repository Separation
By default each Ranorex Studio project contains one repository file which is automatically used for each newly
created recording. You can manage all UI elements of a test suite project in a single repository file, but there are
several reasons for having multiple repositories within a test automation project:

Testing Different User Interfaces


C ommon Repositories for C ommon Modules
Advanced RanoreXPath Repositories for C omplex Identification
Multiple Testers Working on the Same Test Automation Project

Testing Different User Interfaces


If your test suite contains, for example test cases for a web application and tests for a user interface of a client
application, it might be useful to have two repositories. One is used to manage the UI elements of the web
application while the other exclusivily stores the elements from the client hosted application. Although you can
separate things within one repository using simple folders for grouping, it makes sense to divide it up - especially
when working in teams.

Common Repositories for Common Modules

The same way you think about modularization and reusability of small action recordings, the same goes for
repositories. For example when you think about a rich client application using main menus, ribbons or toolbars
you would create small reusable recordings for clicking on the main menu 'File' | 'Open' | 'Handle the Open File
Dialog' | etc. All these reusable modules work with a main menu, a main tool bar or similar common available
controls, and should be based on a repository which exclusively represents commonly used main controls on the
user interface.

Advanced RanoreXPath Expressions

Another reason to build a separate repository could be to store advanced RanoreXPath expressions which should
execlusively be used to create new actions manually instead of recording them.

Mulitple Testers on the Same Project

As long as you're working alone on a test automation project it's not a problem to work with one single
repository. When working in teams and everyone in the team only clicks the 'Record' button to create test
automation modules, it is recommended to keep in mind who is responsible for the main repository. Who is
allowed to rename objects and to re-structure the repository? The main reason to separate repositories is to
avoid accidental damage to repository items which are used by other team members.

Adding a New Repository


Ranorex Studio is able to handle multiple repositories. When performing automated tests on the KeePass
application, this could be useful for testing the complex configuration dialog with a separated repository file to
keep your repositories simple and structured and to provide for possibility of multiple users working on different
repository files.

Add a new repository to your project by clicking the 'Add Repository' button in the Ranorex Studio toolbar. 

Page 84 of 247
Create a new repository file

New repository representing the complex options


dialog in KeePass

Note: It's crucial to understand that repositories are very essential in working with Ranorex and that the basic
principle does not depend on the technology used. Of course it is also possible to create a new repository having
the information for identifying elements on a URL or any other supported technology. This might be useful when
testing the auto-perform functionality in KeePass which assists you in opening the URL and entering the login
information which is stored in a password entry in a semi-automated way. A second, separated repository in
Ranorex Studio could therefore hold all the web elements to verify whether logging in worked or not.
Note: There are some differences in the way the elements in different technologies are identified so the
RanoreXPath is a bit different for different technologies. Once your repository is able to identify the elements in a
robust way, it doesn't matter which technology is behind your test cases. Of course, different technologies can be
tested, combined within one test automation in Ranorex Studio.

Using Mulitple Repositories in Code Modules


Now your test project contains two repository files. While a recording module can only have one repository
assigned, a code module can use multiple repositories.

C#
view plain c opy to c lipboard print 5
[TestModule("C5B0C011-274A-4E54-83DB-0CE28DB95509", ModuleType.UserCode, 1)]   
    public class OptionsCodeModule : ITestModule   
    {   
        // Repository object to access UI elements of KeePass Application   
        MyFirstTestProjectRepository repo = MyFirstTestProjectRepository.Instance;   
        // Repository object to access UI elements of KeePass Options Dialog   
        KeePassOptionsRepository OptionsRepo = KeePassOptionsRepository.Instance;   
           
        /// <summary>   
        /// Constructs a new instance.   
        /// </summary>   
        public OptionsCodeModule()   
        {   
            // Do not delete - a parameterless constructor is required!   
        }   
  
        /// <summary>   
        /// Performs the playback of actions in this module.   
        /// </summary>   
        /// <remarks>You should not call this method directly, instead pass the module   
        /// instance to the <see cref="TestModuleRunner.Run(ITestModule)"/> method   
        /// that will in turn invoke this method.</remarks>   
        void ITestModule.Run()   
        {   
            Mouse.DefaultMoveTime = 300;   
            Keyboard.DefaultKeyPressTime = 100;   
            Delay.SpeedFactor = 1.0;   
               
            // Click the Save-Button in KeePass Mainform   
            repo.KeePass.ButtonSave.Click();   
               
            // Check the option to AutoClear the Clipboard   
            OptionsRepo.FormOptions.TabSecurity.CheckBoxClipboard_auto_clear.Checked = true
  
Page 85 of 247
        }    6
3 4

VB.NET
view plain c opy to c lipboard print

<TestModule("BAA60B6C-5DD1-4EB5-BC39-FDFD65775742", ModuleType.UserCode, 1)> _   
  Public Class UserCodeModule1    
       Implements ITestModule   
  
    ''' Repository object to access UI elements of KeePass Application   
    Private repo As MyFirstTestProjectRepository = MyFirstTestProjectRepository.Instance   
       '' Repository object to access UI elements of KeePass Options Dialog   
       Private OptionsRepo AS KeePassOptionsRepository = KeePassOptionsRepository.Instance
  
       
       ''' <summary>   
       ''' Constructs a new instance.   
       ''' </summary>   
       Public Sub New()   
           ' Do not delete - a parameterless constructor is required!   
       End Sub  
       
    TestRepository repo = TestRepository.Instance;   
  
       ''' <summary>   
       ''' Performs the playback of actions in this module.   
       ''' </summary>   
       ''' <remarks>You should not call this method directly, instead pass the module   
       ''' instance to the <see cref="TestModuleRunner.Run(Of ITestModule)"/> method   
       ''' that will in turn invoke this method.</remarks>   
       Sub Run() Implements ITestModule.Run   
           Mouse.DefaultMoveTime = 300   
           Keyboard.DefaultKeyPressTime = 100   
           Delay.SpeedFactor = 1.0   
           
        ''' Click the Save-Button in KeePass Mainform   
           repo.KeePass.ButtonSave.Click   
              
           ''' Check the option to AutoClear the Clipboard   
           OptionsRepo.FormOptions.TabSecurity.CheckBoxClipboard_auto_clear.Checked = true
  
       End Sub  
  
   End Class  

C opyright © 2012 Ranorex

Page 86 of 247
Repository Settings Dialog
There are two ways to open the 'Settings' dialog for the repository:

C licking the 'Settings' button within Ranorex Spy


C licking the 'Settings' button within Ranorex Recorder

Open 'Settings' from Recorder

Open 'Settings' from Spy

Within the 'C urrent Repository' tab you can specify the class name and the namespace of the automatically
generated source code for the current repository.

On the 'Repository Default' tab page you can specify defaults for the same for newly created repositories.
Additionally, the timeouts used for newly created repository folders and items can by simply changed in the
'Timings for new entries' group box.

The settings 'Enable folder caching' can be unchecked to turn off folder caching for all items by default. Uncheck
the checkbox 'Enable folder autogeneration' to prevent the repository from creating rooted folders automatically.

Current settings of a repository Default repository configuration

Repository Troubleshooting - Folder Caching


In some situations, repository items cannot be found because the caching information of the item's parent folder
is incorrect. In such cases, replaying the steps involving these items may only work part of the time or only with
long delays.

This is caused by a fallback mechanism which is used to search for an item without using the cache if the first
attempt fails. If this occurs, it is recommended to disable the folder cache for the item's parent folder by setting
the 'Use C ache' property to 'False'.

C opyright © 2012 Ranorex

Page 87 of 247
Repository Items Properties
Each repository item (app folder, rooted folder, simple folder and item) held by a repository has a number of properties.

These properties can be altered by opening the representing properties tab which can be accesses by right-clicking the wanted repository item and choosing “Properties” in
opened context menu.

Open repository items properties

Repository items properties

Within the properties tab following properties are available:

Absolute Path The “Absolute Path” represents the path to the repository item including the paths all parent folder. This property is read-only.
With the “Adapter Type” property the adapter type of the repository item can be changed. The best fitting adapter will be chosen by setting this
Adapter Type
property to default.
The “Effective Timeout” property represents the sum of the search timeouts for the specific repository item and all its parent folders. This
Effective Timeout
property is read-only.
Live Element The “Live Element” represents the control specified by the repository item found in the lice system as it is shown in Ranorex Spy.
Name The “Name” property defines the name of the repository item.
Search Timeout The “Search Timeout” property defines the amount of time an element will be searched for, before throwing exception.
Use Ensure Visible The "Use Ensure Visible" property specifies whether the repository item should be forced to become visible before automation or not.

Additionally to the properties mentioned in the table above, a rooted folder or an app folder has the following property:

Page 88 of 247
The “Use C ache” property will either enable or disable caching for the specific folder. The chapter Repository Troubleshooting - Folder C aching
Use C ache
will give more information about folder caching.

C opyright © 2012 Ranorex

Page 89 of 247
Lesson 7: Code Modules
Though a Ranorex Recording with only smart actions, variables and user code capabilities is good enough to
create robust test automation modules, it might be useful or preferable to write pure Ranorex automation code.
In the following section you learn how to create a new code module which automates the process of adding a new
credential data set to the KeePass application.

C reating C ode Module


Using Repository within C ode Module
Using Variables with C ode Modules
Using C ode Modules within Test C ases

Creating Code Module


C reate a new code module by clicking the 'Add C ode Module' button at the toolbar.

Adding a new code module with the toolbar button

Alternatively you are able to add a new code module by using the context menu in the Test Suite.

Adding a new code module using the context menu

Page 90 of 247
Specifying the name used for the code module

After clicking the 'C reate' button a new file is added to the project and automatically opened in the file view.
Ranorex Studio creates a new test module class which contains a 'Run' method that is ready to be extended with
test automation code.

C#
view plain c opy to c lipboard print

namespace KeePass   
{   
    /// <summary>   
    /// Description of AddCredentialEntry.   
    /// </summary>   
    [TestModule("03F5603B-0DDC-49AA-8C26-4D8088260C66", ModuleType.UserCode, 1)]   
    public class AddCredentialEntry : ITestModule   
    {   
        /// <summary>   
        /// Constructs a new instance.   
        /// </summary>   
        public AddCredentialEntry()   
        {   
            // Do not delete - a parameterless constructor is required!   
        }   
  
        /// <summary>   
        /// Performs the playback of actions in this module.   
        /// </summary>   
        /// <remarks>You should not call this method directly, instead pass the module   
        /// instance to the <see cref="TestModuleRunner.Run(ITestModule)"/> method   
        /// that will in turn invoke this method.</remarks>   
        void ITestModule.Run()   
        {   
            Mouse.DefaultMoveTime = 300;   
            Keyboard.DefaultKeyPressTime = 100;   
            Delay.SpeedFactor = 1.0;   
        }   
    }   
}  

VB.NET
view plain c opy to c lipboard print

Namespace KeePass   
    ''' <summary>   
    ''' Description of AddCredentialEntry.   
    ''' </summary>   
    <TestModule("03F5603B-0DDC-49AA-8C26-4D8088260C66", ModuleType.UserCode, 1)> _   
    Public Class AddCredentialEntry   
        Implements ITestModule   
        ''' <summary>   
        ''' Constructs a new instance.   
        ''' </summary>   
                ' Do not delete - a parameterless constructor is required!   
        Public Sub New()   
Page 91 of 247
        End Sub  
  
        ''' <summary>   
        ''' Performs the playback of actions in this module.   
        ''' </summary>   
        ''' <remarks>You should not call this method directly, instead pass the module   
        ''' instance to the <see cref="TestModuleRunner.Run(ITestModule)"/> method   
        ''' that will in turn invoke this method.</remarks>   
        Private Sub ITestModule_Run() Implements ITestModule.Run   
            Mouse.DefaultMoveTime = 300   
            Keyboard.DefaultKeyPressTime = 100   
            Delay.SpeedFactor = 1.0   
        End Sub  
    End Class  
End Namespace  

Using Repository within Code Module


In the same way you use a repository in the recording to identify UI elements for automation, you can also use it
in code. Simply add a new private member which represents the repository to your code module class as shown
below:

C#
view plain c opy to c lipboard print

public class AddCredentialEntry : ITestModule   
{   
    // Repository object to access UI Elements   
    MyFirstTestProjectRepository MyRepo = MyFirstTestProjectRepository.Instance;   
       
    /// Constructs a new instance.   
    public AddCredentialEntry()   
    {   
        // Do not delete - a parameterless constructor is required!   
    }   
       
    void ITestModule.Run()   
    {   
        Mouse.DefaultMoveTime = 300;   
        Keyboard.DefaultKeyPressTime = 100;   
        Delay.SpeedFactor = 1.0;   
           
        // Click 'Add Entry' Button MainMenu   
        MyRepo.MainForm.Edit.Click();   
        MyRepo.KeePass.AddEntry.Click();   
           
        // Set text fields   
        MyRepo.AddEntry.TabSheetAddEntry.Title.TextValue = "WordPressDemo";   
        MyRepo.AddEntry.TabSheetAddEntry.UserName.TextValue = "admin";   
        MyRepo.AddEntry.TabSheetAddEntry.Password.TextValue = "demo123";   
        MyRepo.AddEntry.TabSheetAddEntry.Repeat.TextValue = "demo123";   
        MyRepo.AddEntry.TabSheetAddEntry.URL.TextValue = "bitly.com/wp_demo";   
           
        // Choose an icon   
        MyRepo.AddEntry.TabSheetAddEntry.MBtnIcon.Click();   
        MyRepo.IconPicker.LI_Icon.Click(Location.CenterLeft);   
        MyRepo.IconPicker.ButtonClose.Click();   
           
        // Set Expires   
        MyRepo.AddEntry.TabSheetAddEntry.MBtnStandardExpires.Click();   
        MyRepo.KeePass.MI_Expires.Click();   
           
        // Save Credential Entry   
        MyRepo.AddEntry.ButtonOK.Click();   
    }   
}  

VB.NET
Page 92 of 247
view plain c opy to c lipboard print

Public Class AddCredentialEntry   
    Implements ITestModule   
  
    ' Repository object to access UI Elements   
    Private MyRepo As MyFirstTestProjectRepository = MyFirstTestProjectRepository.Instance
  
  
    ''' Constructs a new instance.   
            ' Do not delete - a parameterless constructor is required!   
    Public Sub New()   
    End Sub  
  
    Private Sub ITestModule_Run() Implements ITestModule.Run   
        Mouse.DefaultMoveTime = 300   
        Keyboard.DefaultKeyPressTime = 100   
        Delay.SpeedFactor = 1.0   
  
        ' Click 'Add Entry' Button MainMenu   
        MyRepo.MainForm.Edit.Click()   
        MyRepo.KeePass.AddEntry.Click()   
  
        ' Set text fields   
        MyRepo.AddEntry.TabSheetAddEntry.Title.TextValue = "WordPressDemo"  
        MyRepo.AddEntry.TabSheetAddEntry.UserName.TextValue = "admin"  
        MyRepo.AddEntry.TabSheetAddEntry.Password.TextValue = "demo123"  
        MyRepo.AddEntry.TabSheetAddEntry.Repeat.TextValue = "demo123"  
        MyRepo.AddEntry.TabSheetAddEntry.URL.TextValue = "bitly.com/wp_demo"  
  
        ' Choose an icon   
        MyRepo.AddEntry.TabSheetAddEntry.MBtnIcon.Click()   
        MyRepo.IconPicker.LI_Icon.Click(Location.CenterLeft)   
        MyRepo.IconPicker.ButtonClose.Click()   
  
        ' Set Expires   
        MyRepo.AddEntry.TabSheetAddEntry.MBtnStandardExpires.Click()   
        MyRepo.KeePass.MI_Expires.Click()   
  
        ' Save Credential Entry   
        MyRepo.AddEntry.ButtonOK.Click()   
    End Sub  
End Class  

Note: By default the class name of a repository is the same as the repository file name (*.rxrep) shown in the
project's view.

Now the class uses a private member referring to repository in order to reuse some of the objects ('Title',
'Username', 'Password', 'PasswordRepeat' and 'URL') within the 'Run' method.

Repository used within code example

Depending on the structure of your repository, accessing items in code might become more and more complex.
To reduce complexity - especially when UI elements are used more than once - you should use local variables
instead of coding the whole structure of your repository everytime you need to automate a UI element.

C#
view plain c opy to c lipboard print

var ButtonOK = MyRepo.FormAdd_Entry.ButtonOK;   
ButtonOK.Click();  
Page 93 of 247
VB.NET
view plain c opy to c lipboard print

Dim ButtonOK = MyRepo.FormAdd_Entry.ButtonOK   
ButtonOK.Click()  

To create local variables as shown in the code above, simply drag and drop elements from the repository
browser directly into the code.

Note: If the repository itself is not already part of the class (e.g. newly created code modules), a local variable
for the repository is generated too

Using Variables with Code Modules


In order to use values provided by a data connector within your code modules, you need to add variables to the
code. Use the context menu item 'Insert Module Variable'.

Add a new variable to your code module

Specify the variable name and the default value

By addding a new variable Ranorex Studio inserts a new code fragment at the current cursor position. A variable
implementation consists of a public property '<VaribleName>' and a private member '_<VariableName>'.

C#
view plain c opy to c lipboard print

string _varTitle = "Wordpress Credentials";   
[TestVariable("9348A7E6-80B6-4A2B-9CBF-0276A236AA3E")]   
public string varTitle   
{   
    get { return _varTitle; }   
    set { _varTitle = value; }   
}  

VB.NET
view plain c opy to c lipboard print

Private _varTitle As String = "Wordpress Credentials"  
<TestVariable("9348A7E6-80B6-4A2B-9CBF-0276A236AA3E")> _   
Page 94 of 247
Public Property varTitle() As String  
    Get  
        Return _varTitle   
    End Get  
    Set  
        _varTitle = value   
    End Set  
End Property  

Now create additional variables for the 'Username', 'Password' and 'URL'. All the module variables will appear
immediately in the module browser.

Appearance of module
variables in module browser

Accessing Repository Variables with the Use of Setter Methods


To bind repository variables to external data when accessing the repository element via the code module, you
have to create a new module variable to act as a bridge. You can use the setter method for the public variable to
also set the repository variable.

Variables used by the repository (e.g. 'varExpires' for the Menu Item in the context menu of KeePass's 'Add Entry
Dialog') are easily accessible via the repository, even from code. In order to bind these variables to external data
(e.g. one row in our Excel file) in a code module you have to create a new module variable to act as a bridge
between external data and repository variables. Following such an approach, it is obviously best to use the setter
methods for public variables. A public variable's setter method is called every time the value of this variable is
set; i.e. assigning the value to the private variable holding the information for the public one. This method can
easily be extended in order to set the repository variable as well.

First two new module variables, 'varExpires' and 'varIconIndex', have to be created the same way as was shown
for 'varTitle', 'varPassword'. After that, a simple code line has to be inserted into the setter method for each
variable. This code line is used for also assigning the passed value to the repository variable and facilitates
binding to external data.

C#
view plain c opy to c lipboard print

string _varRepoIconIndex = "1";   
[TestVariable("EF09BC93-3447-4AC2-9DEB-FE3D78ED5538")]   
public string varRepoIconIndex   
{   
    get { return _varRepoIconIndex; }   
    set {    
        _varRepoIconIndex = value;   
        // Additionally set the Repository Variable in Setter-Method   
        MyRepo.varIconIndex = _varRepoIconIndex;   
            }   
}   
  
string _varRepoExpires = "1 Year";   
[TestVariable("D0A54427-68FF-4B9D-B861-4882BCEC846B")]   
public string varRepoExpires   
{   
    get { return _varRepoExpires; }   
    set {    
        _varRepoExpires = value;   
        // Additionally set the Repository Variable in Setter-Method   
        MyRepo.varExpires = _varRepoExpires;       
         }   
}  

Page 95 of 247
VB.NET
view plain c opy to c lipboard print

Private _varRepoIconIndex As String = "1"  
<testvariable("ef09bc93-3447-4ac2-9deb-fe3d78ed5538")> _   
Public Property varRepoIconIndex() As String  
    Get  
        Return _varRepoIconIndex   
    End Get  
    Set  
        _varRepoIconIndex = value   
        ' Additionally set the Repository Variable in Setter-Method        
        MyRepo.varIconIndex = _varRepoIconIndex   
    End Set  
End Property  
  
Private _varRepoExpires As String = "1 Year"  
<testvariable("d0a54427-68ff-4b9d-b861-4882bcec846b")> _   
Public Property varRepoExpires() As String  
    Get  
        Return _varRepoExpires   
    End Get  
    Set  
        _varRepoExpires = value   
        ' Additionally set the Repository Variable in Setter-Method                
        MyRepo.varExpires = _varRepoExpires   
    End Set  
End Property  
</testvariable("d0a54427-68ff-4b9d-b861-4882bcec846b")></testvariable("ef09bc93-3447-4ac2-
9deb-fe3d78ed5538")>  

Thus the two rows in the Excel file containing such items as the icon index can be bound to these module
variables. This binding causes the variables to be set for each iteration in the test case. During the setting of
those variables, the extended functionality also set's the repository variable assuring that the correct icon will be
used and clicked in the ongoing example.

Using Code Modules within Test Cases


The code module implemented above is now ready to be started by a test case. Add a new test case
('TC _AddEntryFromC ode') to your test suite and reuse already existing modules to start KeePass, login at the
beginning and to validate, delete, save and close it at the end of the test case. You can use the drag and drop
feature to quickly insert the newly created code module into the test case.

Drag and drop the code module into a test case and
combine it with recordings

Now you can reuse the existing data connector created during Lesson 3: Data-Driven Testing with your new test
case.

Page 96 of 247
Reuse the existing data connector by choosing Bind the newly created variables to the data
the item from the drop-down field connector's columns, i.e. columns from the
Excel file

C opyright © 2012 Ranorex

Page 97 of 247
Lesson 8: Reporting
By default each run of a test suite, a test case or a single recording generates a report file (*.rxlog) which tells
you if the run was successful or not. In the following lesson you will learn about the following:

Reading Ranorex Reports


Report Levels
Logging Individual Information

Reading Ranorex Reports


After executing a test suite in Ranorex Studio the generated report file is shown in the file view as shown below.

Ranorex report after running a test suite

The report shown after running a test suite provides a general overview of how many of the test cases have been
executed successfully, failed or blocked. Each executed test case and all its child modules can be analyzed more
in depth by expanding a particular test case.

In addition a test suite report also informs you about the following:

System information like execution time, machine name, operating system, screen dimensions, language,
duration
Global parameter values

If a test case uses local parameter values or external test data, the report shows the values used during
automation as shown below.

Page 98 of 247
Detailed view of a test case report

The low level log messages generated by a recording or by a code module shown in the figure above consist of a
time stamp, a report level, a category and message text. By default logging is turned on for recordings. Use the
Recorder's settings dialog to change the default value and to turn off logging for new recordings. In order to turn
logging off or on for a particular action item, open the properties and set the 'Use Default Logging' attribute to
false.

Jump to Item and Analyze with Spy


Expand the report as shown above and move the mouse pointer over the first log message.

Debug a test run with quick links 'Jump to Item' and 'Open in Spy'

C lick at 'Jump to Item' to open the module and to focus on the source action item. Use the quick link 'Open in
Spy' to analyze the RanoreXPath expression used for the particular action item. This is especially useful in
situations when a test run fails with the message 'Failed to find item...' error message.

Filter Log Messages


Use the checkboxes shown at the top of each module to filter log messages.

Filter for different log levels

Report Folder
For each run of a test suite, a single test case or a recording a new log file (*.rxlog) is generated and saved in
the project's 'Report' folder. You can open older report files by double-clicking the file in the project view. Specify
the file names used for the report files within the test suite's settings dialog.

Log file history within Ranorex Studio project

Note: It is not required to run Ranorex Studio to open a report file. You can also open the report file from
Windows Explorer. If you're going to copy or send the file by email, always ensure that the stylesheet file
'RanorexReport3.xsl' is located in the same target directory.

Report Levels
Within Ranorex you are able to use different levels of reporting information importance, from a debug message
to a failure information. In addition to predefined report levels, you can also easily define your own levels of
report information.
Page 99 of 247
Report Levels describe the importance of a message that is delivered to the report. Since extensive test cases
lead to extensive reports, the usage of different kinds of report levels can assist you making your reports better
arranged depending on your needs.

Within a test suite or even within a test case, you are able to define a report level that describes the minimum
level of reporting information (see Lesson 4: Ranorex Test Suite - Test Suite Settings for more information).
Report information with a lower level of importance is ignored and does not fill up your report, whereas
decreasing a test case's report level could assist you finding an error in your testing scenario.

Predefined Report Levels


Ranorex provides the following predefined report levels - the level itself is indicated with integer values (which
are written in parenthesis):

Debug (10)
Info (20)
Warning (30)
Error (40)
Success (110)
Failure (120)

The first five items describe different levels of reporting importance and meaning. For instance an error message
in the report indicates a logical test step error whereas a warning message should only get your attention but not
indicate an error.

From report levels 'Debug' to 'Success', the result of the current module is still classified as a success whereas
the 'Failure' report level classifies the module result as a failure; this is indicated by a red mark in the report.

Report indicating a failed module

Additionally, at the top of a test case, warnings are indicated with a message with a yellow background.

A report message about warning level results in a highlighted area at


the top of the report

Note: A report message, regardless of its level, never breaks the execution of a test case.
Note: A test case's failure depends on whether a Ranorex exception has been thrown or not. This could
automatically happen if a validation step fails or a new Ranorex exception is thrown.

User-defined Report Levels


In addition to predefined report levels, you are able to define your own report level with dedicated importance
(integer value). You can do that either from code or within the Recorder (see Logging Individual Information for
detailed information).

Logging Individual Information


Individual information can be sent to the report either by using usercode (i.e. code modules) or by using the
recorder action 'Report'.

Logging Information via Code


You can use one of the following methods from Ranorex report class in order to report information on a specific
Page 100 of 247
reporting level:

Ranorex.Report.Debug ("Debug Message");


Ranorex.Report.Info ("Information Message");
Ranorex.Report.Warn ("Warning Message");
Ranorex.Report.Error ("Error Message");
Ranorex.Report.Success("Success Message");
Ranorex.Report.Failure("Failure Message");

Category
These methods can be used with one parameter indicating the 'message' itself. Alternatively they can be used
with an additional parameter indicating the category which is set to the default value 'User' in the first overload of
such methods. The default category can also be set via code by assigning the 'Ranorex.Report.DefaultC ategory'
property. The category can be seen in a distinct column in the report. The following code lines using different
reporting methods (and different reporting categories) lead to a report which is shown after the code example.

C#
view plain c opy to c lipboard print

// Reporting information (debug, info) using default Category "User"   
Ranorex.Report.Debug("This is a Debug Information");   
Ranorex.Report.Info("This is a Information");   
  
// Setting Parameter Category to specific value and report a warining and an error   
Ranorex.Report.Warn("Specific Category","This is a Warning Information");   
Ranorex.Report.Error("Specific Category", "This is an Error Information");   
  
// Setting the Default Category   
Ranorex.Report.DefaultCategory = "My new default category";   
  
// Reporting information (success, failure) using the new default category   
Ranorex.Report.Success("This is a success information");   
Ranorex.Report.Failure("This is a failure Information");  

VB.NET
view plain c opy to c lipboard print

' Reporting information (debug, info) using default Category "User"   
Ranorex.Report.Debug("This is a Debug Information")   
Ranorex.Report.Info("This is a Information")   
  
' Setting Parameter Category to specific value and report a warining and an error   
Ranorex.Report.Warn("Specific Category", "This is a Warning Information")   
Ranorex.Report.Error("Specific Category", "This is an Error Information")   
  
' Setting the Default Category   
Ranorex.Report.DefaultCategory = "My new default category"  
  
' Reporting information(success, failure) using the new default category   
Ranorex.Report.Success("This is a success information")   
Ranorex.Report.Failure("This is a failure Information")  

Page 101 of 247


Report with different reporting methods and categories indicating the
different levels of importance

Note: Please consider that the report information at the error level with the category 'Module' (last entry)
provides a screenshot and moreover, two entries above screenshots are provided in order to visually retrace that
last steps that lead to the current error.

User-defined Report Levels


You are able to define your own report levels with dedicated name and a value for the level:

C#
view plain c opy to c lipboard print

Ranorex.ReportLevel MyNewReportLevel = new ReportLevel("My low Report Level", 25, null);   
Ranorex.Report.Log (MyNewReportLevel, "This is unimportant information");  

VB.NET
view plain c opy to c lipboard print

Dim MyNewReportLevel As Ranorex.ReportLevel = New ReportLevel
("My low Report Level", 25, Nothing)   
Ranorex.Report.Log(MyNewReportLevel, "This is unimportant information")  

Depending on the current Report Level (see next chapter), the report information with user-defined report level
should appear in the report as follows:

Report with information for a user-defined level

Current Report Level

Report information on differing levels of importance only appears in the report if the parent test case has a report
level setting lower than or equal to the current report information level. The current report level can also be set
using code:

C#
view plain c opy to c lipboard print
Page 102 of 247
Ranorex.Report.CurrentReportLevel = Ranorex.ReportLevel.Parse
("Only Highest Importance;90");  

VB.NET
view plain c opy to c lipboard print

"Ranorex.Report.CurrentReportLevel = Ranorex.ReportLevel.Parse
("Only Highest Importance;90")  

This assignment causes the inclusion of reporting information only at a level greater the or equal to 90, which is
'Success' and 'Failure'. The resulting report, which is caused by the same code from above but with a different
current report level, can be seen below.

Report with a current report level of 90

Note: The current report level can always be overridden by logging information with the report level 'Always'.

C#
view plain c opy to c lipboard print

Ranorex.Report.Log (Ranorex.ReportLevel.Always, "User", "Any-Case message");  

VB.NET
view plain c opy to c lipboard print

Ranorex.Report.Log (Ranorex.ReportLevel.Always, "User", "Any-Case message")  

Reporting Screenshots
Screenshots of the current state of the system under test or any UI element can be easily sent to the report.

C#
view plain c opy to c lipboard print

Ranorex.Report.Screenshot (MyRepo.KeePass.Toolbar.Self);  

VB.NET
view plain c opy to c lipboard print

Ranorex.Report.Screenshot(MyRepo.KeePass.Toolbar.Self)  

Screenshot of KeePass toolbar opened directly in Ranorex report

If you call the screenshot method without any arguments, a screenshot of the whole desktop will be available in
your report.
Note: Screenshots from UI elements can only be made if the element is visible at the time a screenshot is made.
C ontrolling your application using code does not necessarily bring your application to the front and make it
Page 103 of 247
visible. To ensure the visibility of UI elements, use the 'EnsureVisible' method which is provided by any element
that is derived from Ranorex Adapter class (e.g. 'Text', 'RadioButton', 'Button', etc.). C onsequently, rooted
folders from repository or even application folders do not ensure visibility. Alternatively you can ensure visibility
by using the 'Self' property from that object types (rooted folder or application folder).}

Reporting System Summary


The Ranorex reporting class provides a way to simply report a system summary:

C#
view plain c opy to c lipboard print

Ranorex.Report.SystemSummary();  

VB.NET
view plain c opy to c lipboard print

Ranorex.Report.SystemSummary()  

System summary provided by reporting function

Logging Information from Recorder


The Ranorex Recorder provides a way to send information directly to the report. Just use the 'Add New Action'
button from the toolbar and add a 'Report' Action.

Add a new report action to your recording

Predefined Report Level


Just like a call from code, you can specify one of the predefined report levels directly within the recorder's action
table. Naturally you can also type in an information message.

Page 104 of 247


Define the report level

Custom Report Level


Report messages with a custom report level can also be submitted. Simply choose the 'C ustom' report level in
the drop-down.

Define a report message with a custom level

Screenshots and Snapshots


Since Ranorex Version 3.3, you can send screenshots and even snapshots to your report directly from the
recorder's action table. These two actions requiere an easy connection to any repository item in order to specify
from which object the screenshot or snapshot should be made.

Use of screenshot and snapshot functionality within the report action


in recorder's action table

C opyright © 2012 Ranorex

Page 105 of 247


Lesson 9: Ranorex Spy
As a stand-alone tool the Ranorex Spy provides all the functionality needed to explore and analyze applications
or websites under test - including their controls and UI elements. After starting Ranorex Spy, the element
browser contains all currently running applications from your Windows desktop.

Ranorex Spy - applications and their UI elements

Tracking UI Elements
RanoreXPath Edit Mode
C reating Ranorex Snapshot Files
General Ranorex Settings

The element browser tree shown on the left side represents the computer's desktop with all currently opened
applications. The name of the root node is set to the machine's host name. By selecting one of the elements from
the browser tree, the Spy provides more detailed information about the selected item in the tabs ‘Overview’,
‘Detail’ and ‘Screenshot’ shown on the right. Ranorex recognizes over 30 of the most commonly known types of
UI elements. In Ranorex vocabulary they are called 'adapters'. Every element shown within the element tree of
Ranorex Spy is represented by a Ranorex UI adapter. If Ranorex is not able to specify the type of adapter of a
UI element, it will be displayed as 'Unknown'.

The 'Overview' tab provides the most important view into the details of a UI element. The available attributes and
their values are divided into the following sections:

'General'
Logical adapters like 'Form', 'Button' or 'Text'
Technology related adapters like 'C ontrol', 'Accessible' or 'NativeWindow'

Page 106 of 247


Ranorex Spy 'Overview' tab divided
into three attribute sections

General
Regardless of what type of UI element is currently selected the 'General' section provides information about
whether the element is enabled, valid or visible.

Logical adapters like 'Form', 'Button' or 'Text'


Regardless of what technology is used from the application under test, Ranorex tries to abstract it with logical
adapters. These adapters are also used within repositories and provide class specific attribute values like the text
value or the state of a button.

Technology related adapters like 'Control', 'Accessible' or 'NativeWindow'


This type of adapter is used to group technology related information like the 'C ontrolName' of a .NET WinForms
button or the process name of an application.

All attributes shown within this tab are accessible during an automated test for validation. Depending on the type
of a UI element, they may also be used to set values. Learn more about how to use different adapters to read
and set attribute values here.

In addition all attributes can be used within the RanoreXPath. By default the attribute written in bold is
automatically used to identify the UI element.

Attribute 'controlName' is used to identify the button

The RanoreXPath expression shown in the figure above can be seen as a navigation path through the element
browser tree used to identify a UI element. You can use the RanoreXPath editor to change element identification
or edit the path expression directly within the text box's RanoreXPath edit mode.

Short Introduction to the Structure of RanoreXPath


The RanoreXPath is built up in a hierarchical way where all the layers are separated with a 'forward slash' (/).
The following figure shows an abstract illustration of the way one layer is induced with a so called adapter (e.g.
form, button, etc.). Since there may be more than one UI elements of a specific type (adapters) on the current
level of the path, the desired adapter itself is commonly specified in more detail; this is done in a specification
Page 107 of 247
fragment surrounded by a pair of square brackets. You can also specify the intended adapter with the use of an
index (e.g. button[2]). As already mentioned, specification is commonly done with one or more attributes, where
the attribute is prefixed with an @ sign followed by an equation operator (=, !=, ~, > as well as >, >=, <, <=)
and an attribute. For more information about equation operators please have a look at Lesson 10: RanoreXPath
Editor - Types of Equations.

Abstract illustration of the structure of RanoreXPath

Attribute equations may also be combined with 'and' and 'or' operators (e.g. button[@text='OK' and
@enabled='true']).

Capture Screenshot Files for Image-Based Search


Use the context menu item 'C apture Screenshot' to create an image file (PNG format) which can be used to
search for images in test automation code.

Capture a screenshot from a UI element to save as PNG file

Specify the image region using the toolbar button 'Select Image Region' and click the 'Save' button to save the
selected region as a PNG file.

Page 108 of 247


Select an image region to save

Toolbar shortcuts  

Browse Local Host Shows currently running host applications

Refresh Updates the current state of applications

Load from Snapshot Loads an existing Ranorex snapshot file

Save as Snapshot Saves all UI elements from the tree view to a Ranorex snapshot file

Highlight Elements When switched on, highlights selected UI elements on the users desktop

Apply Applies the changes in RanoreXPath

 
Context menu

Add to Repository Adds the current element to a Ranorex Repository

Set Element as Root Sets the currently selected element as root element

Refresh Updates all attributes of the specified UI element

Saves the current UI element including the child structure to a Ranorex


Save as Snapshot
snapshot file
Add C lass or Process Name to Specifies whether the element's class or process name should use the
GDI C apture List GDI plug-In to turn on text-based object recognition

Highlight Element Highlights the current element

C aptures a screenshot from the current element to be used for further


C apture Screenshot...
image-based validation

Note: Saved screenshots can also be used for image comparison in code, for example for finding and comparing
images or image-based automation. For more information about this, please have a look at the code examples.

C opyright © 2012 Ranorex

Page 109 of 247


Tracking UI Elements
You can navigate manually through the Ranorex Spy's element tree or use element tracking to identify UI
elements in your application under test. The Ranorex Spy supports two ways of tracking UI elements:

Using the TRAC K Button


How to Track Menu Items - 'Instant Tracking'

Using the TRACK Button


C lick the 'TRAC K' button to start tracking a UI element. Move your mouse pointer over a specific control (e.g.
button, text box) so that the currently identified object is highlighted. By clicking the control, the tracking mode
will be stopped and all information on the selected UI element will be shown within Ranorex Spy.

Click the 'Track' button to start element tracking

Note: To abort the tracking session press <ESC > or click the 'TRAC K' button again.

In some cases it might be necessary to track UI elements which are currently behind the Ranroex Spy window.
Simply uncheck the 'Always On Top' checkbox to cause Ranorex Spy to minimize during the tracking process.

'Always On Top' checkbox within Ranorex Spy

How to Track Menu Items - 'Instant Tracking'


When tracking menu or pop-up items, you use the ‘Instant Tracking’ method by using a shortcut to select a UI
element. Simply move your mouse pointer over a menu item and press the <C TRL> + <Win> key combination
to instantly track the UI element. ‘Instant Tracking’ is not only available for popup items; this tracking mode can
also be used for all other UI elements.

Page 110 of 247


Instant tracking of menu items

C opyright © 2012 Ranorex

Page 111 of 247


RanoreXPath Edit Mode
There are two ways to change the RanoreXPath expression. One is to work with the RanoreXPath editor which
can be opened using the magic wand in the textbox. The second option is to edit the path directly in the textbox
of Ranorex Spy; this is described in the following section.

To support the editing of RanoreXPath expressions, the editor textbox provides an auto completion feature which
helps to avoid syntax errors and to speed typing. By pressing the key combination <C TRL>+<SPAC E> at any
time, the RanoreXPath editor suggests a list of suitable keywords, attributes or syntax codes.

RanoreXPath auto completion

The RanoreXPath editor mode is indicated with a yellow highlighted text box. In edit mode, RanoreXPath is used
as a query to filter UI elements as follows:

Use of RanoreXPath as a filter to search for buttons

The result is presented directly within the Ranorex Spy tree. All matching items are highlighted in yellow. In
addition the result can easily be added to a repository by selecting the menu item 'Add Matching C hildren to
Repository'.

Page 112 of 247


Add matching items to the repository

To stop the edit mode, click the red cancel button which is located in the RanoreXPath edit box.

Stop RanoreXPath edit mode

C opyright © 2012 Ranorex

Page 113 of 247


Creating Ranorex Snapshot Files
With the Ranorex snapshot feature, you can not only save graphic but also UI structure information into an XML
file (*.rxsnp). C reate and send a snapshot by email to support ranorex.com to request application
specific assistance from the Ranorex team. Based on the information stored in the snapshot, the support team
will be able to anaylze your application under test offline and give advice on how to optimize unique object
identification with RanoreXPath.

Saving UI structure of KeePass as Ranorex Spy tool with opened


a snapshot file snapshot file from KeePass

Use the context menu item 'Save as Snapshot' within Ranorex Spy to store all elements, dialogs and applications,
including their sub-items into a single Ranorex snapshot file.

Note: In order to save screenshot information correctly, activate the desired application for which you wish to
create a snapshot before saving.

Snapshots from pop-up windows, drop-down combo boxes or drop-down menus


For creating a snapshot from the 'File' menu pop-up of KeePass, you can use the shortcut key <SC ROLL> in
combination with the instant tracking feature of Ranorex Spy:

1. Open Ranorex Spy and activate 'Highlight Elements'.


2. Start the KeePass application and open the 'File' menu.
3. Track the parent menu container window of the menu items. Track the pop-up frame by mousing over the
edge of the window and pressing <C TRL>+<Win>.
4. Press the <SC ROLL> shortcut to cache the current elements including their underlying items for Ranorex
Spy.
5. Lastly save the current view as snapshot.

Page 114 of 247


Track menu container window using instant tracking
(<CTRL>+<Win>)

C opyright © 2012 Ranorex

Page 115 of 247


General Ranorex Settings
There are three ways to open the 'Settings' dialog to change general Ranorex automation and identification
settings:

C licking 'Settings' button within Ranorex Spy


C licking 'Settings' button within Ranorex Recorder
C licking 'Global Settings' button within Ranorex Studio

Open 'Settings' from Spy

Open 'Settings' from Recorder

Open 'Global Settings' from Ranorex Studio

General settings

General Ranorex settings

'Use Ensure Visible by default'

Specifies whether a UI element used as Ranorex adapter should be forced to become visible before automation
or not. By default this value is automatically used for each repository item.

'Maximum length fo text values in RanoreXPaths'

Specifies the maximum length of attribute values used within RanoreXPath.

Page 116 of 247


'The factor that all timouts of find operations are multiplied with'

Multiplies all repository timeouts with the specified value to prevent test cases from failing in case of different
timing behavior. This is especially useful when executing tests on different system configurations.

Note: The value can also be set at the time of executing a test suite using the test suite's command line
arguments or by directly using the 'Ranorex.Core.Configuration.Current.Adapter.TimeoutFactor' property
in code.

'Reset not shown technology specific limitations'

Resets 'Do not show again' checkbox used to suppress assistance dialog for technology limitations. C lick 'Reset'
to show the dialog again for not instrumented technologies or applications.

Advanced Settings
Most of the settings shown in the 'Advanced' group box are used to configure Ranorex object recognition and
RanoreXPath generation. Please be careful when changing these settings.

'Enable 32/64 Bit Bridge'

Use the checkbox 'Enable 32/64 Bit Bridge' to turn off the bit bridge required to handle 32/64 bit based
applications on 64 bit operating systems automatically.

'Disable expensive attribute in tools'

This setting instructs plug-ins not to evaluate computationally intensive attributes for Ranorex Spy, Recorder, and
Ranorex Studio. If checked, attributes like Row.Index do not have a value for certain technologies when shown in
Ranorex Spy and, in that way, speeding up performance.

'Use asynchronous dispatching of mouse and keyboard events'

This setting is used to turn on or off dispatching of mouse and keyboard events during recording.

'Use hidden screenshot capturing (if possible)'

Tries to create screenshots used for recordings, repositories or Ranorex snapshot files, even for hidden
applications.

'Delay before pressing a key sequence (ms)'

Specifies the time to wait in milliseconds before performing a key sequence simulation.

'RanoreXPath generation tree search depth'

Defines the number of unique RanoreXPath levels required for a unique identification. Note: The higher the
value, the shorter the RanoreXPath strings that are generated. Keep in mind that the shorter the path, the longer
it takes to find the expected UI element.

'GDI Capture Settings...'

Opens the dialog to change the current GDI capture list. More information about the Ranorex GDI plug-In can be
found here.

'Edit Path Weights...'

In order to get assistance with editing RanoreXPath weights, contact the Ranorex support team.

Note: C lick the button 'Restore Defaults' to reset all values to their default values. Use the 'Import...' and
'Export...' buttons to save and load user-specific configurations.

Plug-In Specific Settings

Page 117 of 247


Plug-in specific settings

Plug-in specific settings can be used to alter the behavior of individual Ranorex plug-ins, for example, to achieve
backwards compatibility with older versions. For more information on each setting, read the description shown
when you click on a particular setting in the property grid.

C opyright © 2012 Ranorex

Page 118 of 247


Lesson 10: RanoreXPath Editor
In this section you will learn about

Layout of Advanced RanoreXPath Editor


The Tree View Section
The Attribute Equation Section
Types of Equations
Relationship Operators
Adapter Types
Optional Path Elements
Defining Variables
Live View with Dynamic C apabilities and Offline View

The Advantages of Advanced RanoreXPath Editor


As you might know, the RanoreXPath expression is a powerful identifier of UI elements for desktop and Web
applications.  To learn more about the RanoreXPath click here: RanoreXPath Syntax

The Advanced RanoreXPath Editor assists you in setting up the RanoreXPath of your components in an easy and
well-arranged way. So if you track some UI component with the Ranorex Spy and you want to make the
RanoreXPath of this component more readable or you’d like to simply modify the RanoreXPath you tracked,
before the Advanced RanoreXPath Editor is the tool to use.

How to Access the Advanced RanoreXPath Editor


It's this easy: Everywhere a RanoreXpath is visible in a Ranorex Tool you can edit this RanoreXPath with the
Advanced RanoreXPath Editor.

More precisely, this will apply in Ranorex Repositories and in the Ranorex Spy. You can access the Advanced
RanoreXPath Editor by choosing any UI Element in the repository or in Spy and switch into edit mode of the
corresponding RanoreXPath by simply right-clicking on the path.

Click magic wand to open RanoreXPath editor

C opyright © 2012 Ranorex

Page 119 of 247


Layout of Advanced RanoreXPath Editor
To give you access to the Advanced RanoreXPath Editor, you will now get an overview of the structure of this
editor.
As you can see, you can break down the editor in three areas: the RanoreXPath shown in a tree view on the left
(marked in green), the attribute equation list of the selected tree item on the right (marked in red) and a status
and button section at the bottom (marked blue).

RanoreXPath Editor with three main areas

As you can see, the whole path is shown in this tree structure with each path element as one node of the tree. In
the left section of the editor you can access each of these path elements to alter the attribute equations in the
right section on which the path is based. In the bottom section you can verify and also highlight the adapters
which correspond to the path as well as apply or reject changes on the path you made. Furthermore you can
inspect how many adapters correspond to the currently selected tree item shown at the bottom left of the editor.

The Tree View Section


As described above you can see the whole RanoreXPath you want to edit mapped as a tree structure. For
example if you start KeePass and add two entries, one called 'WordPressDemo' and the other called 'GMail' and
you track the cell holding the username of 'GMail', you will get the following tree structure in the Advanced
RanoreXPath Editor:

Page 120 of 247


KeePass with one cell being tracked by Ranorex Spy

RanoreXPath structure in path editor for a cell in second row

The Attribute Equation Section


In the attribute equation section of the Advanced RanoreXPath Editor you can define the attribute value
comparison which the RanoreXPath is based on. If you want to define the adapter being accessed with different
attributes than the ones being suggested by Ranorex, you are free to change the method of object identification
here by simply checking and unchecking attributes.}
C oncerning KeePass and the data-driven approach (see Lesson 3: Data-Driven Testing) we validated the success
of 'Adding an entry' with the validation of the existence of the entry in the grid. Thus we add two sample entries
(WordPressDemo and GMail) to KeePass. When Ranorex Spy is used to track the username of the GMail entry
(second cell in the second row), the following structure of RanoreXPath results in the path editor window:

RanoreXPath structure for username of GMail entry in KeePass

/form[@controlname='MainForm']/container/container[@caption='' and @controltypename='SplitterPanel' and


@instance='0']/container/container[@caption='' and @controltypename='SplitterPanel' and
@instance='1']/table/row[@index='1']/cell[@text='Ranorex']

What we can see in the RanoreXPath structure (in Advanced RanoreXPath Editor) as well as in the RanoreXPath
itself is that the row (adapter) is indicated with the index attribute (row[@index='1']). This means that the cell
'Ranorex' is only recognized if it is located in the first row. This cell would not be found if an additional row was
inserted above and the index was changed. Also sorting for a column (e.g. column username) could easily lead to
Page 121 of 247
another row index. To avoid a problem concerning the row index, you could change the path with the use of the
RanoreXPath editor to be row independent by unchecking the index attribute checkbox in the row node.

Uncheck the index attribute in the row node

/form[@controlname='MainForm']/container/container[@caption='' and @controltypename='SplitterPanel' and


@instance='0']/container/container[@caption='' and @controltypename='SplitterPanel' and
@instance='1']/table/row/cell[@text='Ranorex']

This path leads to any cell in any row containing the text 'Ranorex'. C oncerning our validation of the success of
adding an entry, it would be more meaningful if the path would lead to the text value 'Ranorex' in any row but
only in the column 'UserName'. Therefore we just open up the RanoreXPath editor again and add the column
index attribute by checking it.

Check the column index attribute

/form[@controlname='MainForm']/container/container[@caption='' and @controltypename='SplitterPanel' and


@instance='0']/container/container[@caption='' and @controltypename='SplitterPanel' and
@instance='1']/table/row/cell[@text='Ranorex' and @columnindex='1']

If another KeePass entry is added which has the same username ('Ranorex'), this path would lead to a multiple
result. You can easily check the result of your XPath in path editor by having a look at the text in the bottom left
corner.

Page 122 of 247


The current path leads to two elements

To find out which elements are found with the current XPath, simply click on the 'Highlight' button on the bottom
of RanoreXPath editor.

The underlying path leads to two elements in KeePass

As you can see, building up a robust and unique path is a crucial task which always depends on the
characteristics of your application. Ranorex tries to support you optimally in that process by being as flexible as
possible.

Types of Equations
Ranorex provides a set of equations which can be used to build up or to modify a RanoreXPath. These equation
operators can be accessed easily via a drop-down in RanoreXPath Editor.

Textual Equations
The following types of equations are defined for textual comparisons:

"=": The value of the attribute must be equal to the given value (case sensitive)
"~": The value of the attribute must match the given regular expression
"!=": The value of the attribute must not be equal to the given value (case sensitive)
">": The value of the attribute must start with the given string (case sensitive)

Numerical Equations
The following types of equations are defined for numerical comparisons (starting with Ranorex Version 3.3):

">": The (numerical) value of the attribute must be greater than the given value
">=": The (numerical) value of the attribute must be greater than or equal to the given value\\
"<": The (numerical) value of the attribute must be less than the given value
"<=": The (numerical) value of the attribute must be less than or equal to the given value

Note: Since the > operator is used for textual and for numerical equations as well, it depends on the type of the
values you are trying to compare; i.e. whether the textual 'Starts with'or the numerical 'Greater than'
functionality is used.

Example for Regular Expression


The following example shows how to use a 'regular expression' operator (~).

Page 123 of 247


Matches all entries ending with the text
fragment 'rex' using a regular expression

Result from the equation above

Note: For more details about regular expression, see RanoreXPath - RanoreXPath with Regular Expressions.

Example for Unequal

The following example shows how to use the 'unequal' operator (!=).

Matches all entries that are not equal to


'Ranorex'

Result from the equation above

Example for Starts With


The following example shows how to use the 'starts with' operator (>).

Matches all entries that start with 'adm'

Result from the equation above

Example for Numerical Equations


The following examples demonstrates how numerical operators (>, >=, < and <=) can be used in the
Page 124 of 247
RanoreXPath Editor.

Matches all rows matching index > 2 and


index <= 3

Result from the equation above

Relationship Operators
After exploring the equation operators, you are next going to learn more about the relationship operators.
Relationship operators define the relationship between the nodes (elements of the path). As a result it is not
necessary to always use a directed path. One element in the path can also be defined using another relationship
to its 'parent' other than being the child of a parent node.}
The following relationship operators are available in the context menu of a node.

Available relationship operators in RanoreXPath editor

child: Refers to all children of the current node


descendant-or-self: Refers to all descendants (children, grandchildren, etc.) of the current node and the
current node itself
ancestor: Refers to all ancestors (parents, grandparents, etc.) of the current node
self: Refers to the current node
descendant: Refers to all descendants (children, grandchildren, etc.) of the current node
parent: Refers to the parent of the current node
ancestor-or-self: Refers to all ancestors (parents, grandparents, etc.) of the current node and the
current node itself
Page 125 of 247
preceding-sibling: Refers to all siblings before the current node 
following-sibling: Refers to all siblings after the current node

The following example describes, how to leave the directed way in the path using relationship operators, e.g. if
you want to refer to a table row containing any cell with the text 'Amazon'. Using the common, directed way of
building up a path, this wouldn't be possible. We start with the path referring to the cell:

/form[@controlname='MainForm']/container/container[@caption='' and @controltypename='SplitterPanel' and


@instance='0']/container/container[@caption='' and @controltypename='SplitterPanel' and
@instance='1']/table/row/cell[@text='Amazon']

We can now move back to the cell's parent using the 'parent' relationship operator. The parent element is a row,
therefore we have to add a new layer manually using the row adapter.

/form[@controlname='MainForm']/container/container[@caption='' and @controltypename='SplitterPanel' and


@instance='0']/container/container[@caption='' and @controltypename='SplitterPanel' and
@instance='1']/table/row/cell[@text='Amazon']/row

We simply open the Advanced RanoreXPath Editor and choose the relationship operator 'parent' in the 'Axis'
submenu.

Contextmenu for defining the relationship operator for currently selected node

This path first describes the way to a cell containing the text 'Amazon' and moves up one layer of hierarchy to the
parent of this cell, which is a row. Highlighting the element leads to the result shown in following figure.

Highlighting the element from the newly created path

Adapter Types
Adapters describe the type of element that is referred to. In the RanoreXPath editor you are able to change the
attribute type easily.
Adapters used within a path, which are primarily suggested from Ranorex, can also be changed easily using the
context menu.

Page 126 of 247


Changing the adapter to a specific element

If you do not want to use a specific adapter, you can use the asterisk adapter ('*') which is an undefined
container for all types of elements. This might be useful if your application has dynamically created elements and
if for some parts of the path, the adapter should not be specified.

Optional Path Elements


Starting with Ranorex Version 3.3 it is possible to mark some parts of a path as optional which means that the
referred elements can be found even if optional parts of the path do not exist.
In some situations it can be useful to mark parts of the path as optional. If you want to refer to the 'Windows'
node within the folder tree in KeePass, this node can be located at the root level but, on the other hand, it could
also be located in a sub node of the tree.

Windows node located at the root ...in a sub-node of the tree (right)
level (left) or... in KeePass

In general, the path to the 'Windows' node on the left side of the figure would not include the 'General' folder
because this folder can be seen as a sibling. The path to the 'Windows' node on the right side, which can be seen
as child element of the 'General' node, would therefore include this element in the path. Thus, the 'General' folder
can somehow be seen as optional if you want to access the 'Windows' node in both cases. Here, the general
folder could be marked as optional which means that regardless whether the 'Windows' folder is a child of the
'General' folder (and therefore is part of the path) or is a sibling of the 'General' folder (which is not part of the
path) the element will be found.

Page 127 of 247


Marking one layer of the path as optional

/form[@controlname='MainForm']/container/container[@caption='' and @controltypename='SplitterPanel' and


@instance='0']/container/container[@caption='' and @controltypename='SplitterPanel' and
@instance='0']/tree/tree/treeitem/treeitem?[@accessiblename='General']/treeitem[@accessiblename='Windows']

Defining Variables
In the RanoreXPath you are able to use variables which can be used for such things as data-driven testing.
Variables can be created easily in the RanoreXPath Editor.
If you start the RanoreXPath editor from an existing repository,, you have an additional button for each
(checked) attribute equation. With these buttons you are able to define variables which can be used for dynamical
alteration of the RanoreXPath.

Buttons for creating a new variable for every checked attribute

Variables can also be created using the 'As


new Variable' entry in the dropdown menu

The variables you have added are inherited from the repository you are working on. Each of the variables held
by the repository can be used as attribute equations. For more details about variables used within the repository,
please have a look at Lesson 3: Data-Driven Testing - Using Variables within the Repository.

Page 128 of 247


Live View with Dynamic Capabilities and Offline View
One additional thing to mention is that if you are in live view, you basically get more information delivered about
the adapter you are working on than being in offline view.

Offline view means working with a snapshot file or working with a repository holding information from a non-
running application.

In live view you are additionally able to use the verify and highlighting functionality.

Starting with Ranorex Version 3.3, you are also able to access dynamic capabilities from adapters in live view.
The following screenshot shows dynamic capabilities from the mainform of KeePass (Winforms).

RanoreXPath editor window in live view having dynamic capabilities

Note: Dynamic capabilities can only be accessed for certain types of technologies (Winforms, Flash/Flex, Web
and Java).

C opyright © 2012 Ranorex

Page 129 of 247


Code Examples
The following code examples explain how to use Ranorex API in order to write code modules or to extend
recording modules with user specific code.

Using Repository in C ode


Wait for UI Elements Using Repository
C reate Adapters to Access More Properties and Methods
C reate a List of Adapters From a Repository Element
Using Validate C lass
Forcing a Test C ase to Fail
Set Up Automation Speed
Accessing Test C ase & Test Suite C ontext
Advanced C ode Examples
How to do image based automation
How to find and compare images
Handling Unexpected Dialogs

Using Repository in Code

C#
view plain c opy to c lipboard print

[TestModule("D451F1D1-C347-4B58-939F-F6187642EB56", ModuleType.UserCode, 1)]   
public class UsingRepository : ITestModule   
{   
    // Repository object to access UI elements   
    MyFirstTestProjectRepository repo = MyFirstTestProjectRepository.Instance;   
       
    /// <summary>   
    /// Constructs a new instance.   
    /// </summary>   
    public UsingRepository()   
    {   
        // Do not delete - a parameterless constructor is required!   
    }   
  
    void ITestModule.Run()   
    {   
        Mouse.DefaultMoveTime = 300;   
        Keyboard.DefaultKeyPressTime = 100;   
        Delay.SpeedFactor = 1.0;   
             
        // Using Ranorex.Form adapter represented by 'MyApp'   
        // 'MyApp' is used as a folder within the repository;    
        // the 'Self' property returns an object of type Ranorex.Form   
           
        // Activates application   
        repo.MyApp.Self.Activate();   
        // Log 'Active' state   
        Report.Info(repo.MyApp.Self.Active.ToString());   
        // Maximize, Minimize and Restore              
        repo.MyApp.Self.Maximize();   
        repo.MyApp.Self.Minimize();   
        repo.MyApp.Self.Restore();   
        // Closes application   
        repo.MyApp.Self.Close();   
               
               
Page 130 of 247
        // Using Ranorex.Button adapter represented by 'ButtonAdd'               
        // Read and log value of 'Text' attribute   
        Report.Info(repo.MyApp.Buttons.ButtonAdd.Text);   
               
        // Press button   
        repo.MyApp.Buttons.ButtonAdd.Press();   
        // Read and log value of 'Enabled' attribute   
        Report.Info(repo.MyApp.Buttons.ButtonAdd.Enabled.ToString());   
               
        // Using Ranorex.RadioButton adapter   
        // represented by 'GenderOption'   
               
        // Select radio button   
        repo.MyApp.GenderOption.Select();   
               
        // Accessing listitems of Ranorex.List adapter   
        // represented by 'CategoryList'   
        IList<Ranorex.ListItem> listItems = repo.MyApp.CategoryList.Items;   
        foreach ( Ranorex.ListItem item in listItems )   
        {   
            Report.Info(item.Text + " is member of CategoryList");   
        }   
               
        // Using Ranorex.MenuItem to open 'File' menu   
        repo.MyApp.MenuItemFile.Select();               
        // Selecting sub menu item 'Connect'   
        repo.FileMenu.Connect.Select();               
        // Read and log 'Enabled' state of menu item 'Connect'   
        Report.Info(repo.FileMenu.Connect.Enabled.ToString());   
    }   
}  

VB.NET
view plain c opy to c lipboard print

Public Class UsingRepository   
    Implements ITestModule   
    ' Repository object to access UI elements   
    Private repo As MyFirstTestProjectRepository = MyFirstTestProjectRepository.Instance   
  
    ''' <summary>   
    ''' Constructs a new instance.   
    ''' </summary>   
            ' Do not delete - a parameterless constructor is required!   
    Public Sub New()   
    End Sub  
  
    ''' <summary>   
    ''' Performs the playback of actions in this module.   
    ''' </summary>   
    ''' <remarks>You should not call this method directly, instead pass the module   
    ''' instance to the <see cref="TestModuleRunner.Run(ITestModule)"/> method   
    ''' that will in turn invoke this method.</remarks>   
    Private Sub ITestModule_Run() Implements ITestModule.Run   
        Mouse.DefaultMoveTime = 300   
        Keyboard.DefaultKeyPressTime = 100   
        Delay.SpeedFactor = 1.0   
        ' Using Ranorex.Form adapter represented by 'MyApp'   
        ' 'MyApp' is used as a folder within the repository;    
        ' the 'Self' property returns a Ranorex.Form object   
  
        ' Activates application   
        repo.MyApp.Self.Activate()   
        ' Log 'Active' state   
        Report.Info(repo.MyApp.Self.Active.ToString())   
        ' Maximize, Minimize and Restore              
        repo.MyApp.Self.Maximize()   
        repo.MyApp.Self.Minimize()   
        repo.MyApp.Self.Restore()   
        ' Closes application   
        repo.MyApp.Self.Close()   
  
Page 131 of 247
  
        ' Using Ranorex.Button adapter represented by ButtonAdd'               
        ' Read and log value of 'Text' attribute   
        Report.Info(repo.MyApp.Buttons.ButtonAdd.Text)   
  
        ' Press button   
        repo.MyApp.Buttons.ButtonAdd.Press()   
        ' Read and log value of 'Enabled' attribute   
        Report.Info(repo.MyApp.Buttons.ButtonAdd.Enabled.ToString())   
  
        ' Using Ranorex.RadioButton adapter   
        ' represented by 'GenderOption'   
  
        ' Select radio button   
        repo.MyApp.GenderOption.[Select]()   
        ' Accessing listitems of Ranorex.List adapter   
        ' represented by 'CategoryList'   
        Dim listItems As IList(Of Ranorex.ListItem) = repo.MyApp.CategoryList.Items   
        For Each item As Ranorex.ListItem In listItems   
            Report.Info(item.Text & " is member of CategoryList")   
        Next  
  
        ' Using Ranorex.MenuItem to open 'File' menu   
        repo.MyApp.MenuItemFile.[Select]()   
        ' Selecting sub menu item 'Connect'   
        repo.FileMenu.Connect.[Select]()   
        ' Read and log 'Enabled' state of menu item 'Connect'   
        Report.Info(repo.FileMenu.Connect.Enabled.ToString())   
    End Sub  
End Class  

Wait for UI Elements Using Repository


Each item and each folder type provides an additional object item declared with '<ObjectName>Info'. It is used to
access item related attributes without accessing the UI element directly in order to prevent Ranorex from
throwing exceptions. The info object is mainly used to check whether an item or a folder path is valid or not. In
combination with the timeout set for the item, you can use it to wait for UI elements like dialogs, text values and
web content.

C#
view plain c opy to c lipboard print

// Use the 'Info' object to check existence of the   
// 'SaveDialog' item; Method 'Exists' uses the timeout    
// specified for the 'SaveDialog' in the repository   
Report.Info("Exists = " + repo.SaveDialog.SelfInfo.Exists().ToString());   
               
// Use the 'Info' object to check existence of the   
// 'TextOnline' item which uses the following RxPath:   
// statusbar/text[@accessiblename='Online']   
// This way you can wait with the timeout specified for   
// the item within the repository for the text 'Online'   
bool statusTextConnected = repo.MyApp.TextOnlineInfo.Exists();   
               
// Using 'Info' objects for validation   
// Throws a Ranorex.ValidationException if validation   
// fails. Automatically reports success or failed message   
// to log file                                 
Validate.Exists(repo.SaveDialog.ButtonOKInfo);   
                           
// Validates the existance of the repository item,   
// but does not throw any exception   
Validate.Exists(repo.SaveDialog.ButtonOKInfo,"Check Object '{0}'",false);  

VB.NET
view plain c opy to c lipboard print

' Use the 'Info' object to check existence of the   
Page 132 of 247
' 'SaveDialog' item; Method 'Exists' uses the timeout    
' specified for the 'SaveDialog' in the repository   
Report.Info("Exists = " & repo.SaveDialog.SelfInfo.Exists().ToString())   
  
' Use the 'Info' object to check existence of the   
' 'TextOnline' item which uses the following RxPath:   
' statusbar/text[@accessiblename='Online']   
' This way you can wait with the timeout specified for   
' the item within the repository for the text 'Online'   
Dim statusTextConnected As Boolean = repo.MyApp.TextOnlineInfo.Exists()   
  
' Using 'Info' objects for validation   
' Throws a Ranorex.ValidationException if validation   
' fails. Automatically reports success or failed message   
' to log file                                  
Validate.Exists(repo.SaveDialog.ButtonOKInfo)   
  
' Validates the existance of the repository item,   
' but does not throw any exception   
Validate.Exists(repo.SaveDialog.ButtonOKInfo, "Check Object '{0}'", False)  

Create Adapters to Access More Properties and Methods


If you analyze the VIP Database application form with Ranroex Spy, you see that that the application window
provides three adapters (Form, C ontrol and NativeWindow). The Ranorex.Form adapter with all attributes and
methods is directly available using the repositorie's application folder 'MyApp'. If you want to access properties
like 'ProcessName' or invoke methods exposed by a .NET WinForms control you need to convert the Form
adapter to NativeWindow or C ontrol. As you can see in the code section below the "...Info" object is used to
create the desired adapter.

C#
view plain c opy to c lipboard print

// Creating adapter of type 'NativeWindow' using the "...Info" object               
Ranorex.NativeWindow nativeWnd = repo.MyApp.SelfInfo.CreateAdapter<Ranorex.NativeWindow>
(false);   
// ... and read value of attribute 'ProcessName'   
Report.Info("Process name of VIP Database: " + nativeWnd.ProcessName);   
                           
// Using Control Adapter to access properties and methods of    
// .NET WinForms control   
Ranorex.Control winFormsControl = repo.MyApp.SelfInfo.CreateAdapter<Ranorex.Control>
(false);   
// Set background color of VIP application to Color.Black using the   
// exposed property 'BackColor'   
winFormsControl.SetPropertyValue("BackColor",Color.Black);   
                           
// Report screenshot after changing the background color   
Report.Screenshot(repo.MyApp.Self);   
// Closes VIP Database by invoking the 'Close' method   
// exposed by the System.Windows.Forms.Form class   
winFormsControl.InvokeMethod("Close");  

VB.NET
view plain c opy to c lipboard print

' Creating adapter of type 'NativeWindow' using the "...Info" object               
Dim nativeWnd As Ranorex.NativeWindow = repo.MyApp.SelfInfo.CreateAdapter
(Of Ranorex.NativeWindow)(False)   
' ... and read value of attribute 'ProcessName'   
Report.Info("Process name of VIP Database: " & nativeWnd.ProcessName)   
  
' Using Control Adapter to access properties and methods of    
' .NET WinForms control   
Dim winFormsControl As Ranorex.Control = repo.MyApp.SelfInfo.CreateAdapter
(Of Ranorex.Control)(False)   
' Set background color of VIP application to Color.Black using the   
' exposed property 'BackColor'   
Page 133 of 247
winFormsControl.SetPropertyValue("BackColor", Color.Black)   
  
' Report screenshot after changing the background color   
Report.Screenshot(repo.MyApp.Self)   
' Closes VIP Database by invoking the 'Close' method   
' exposed by the System.Windows.Forms.Form class   
winFormsControl.InvokeMethod("Close")  

Note: In order to access properties or methods exposed by a WinForms control you need to know their names. If
you're not familiar with the control's API ask the developer of your application for assistance.

Create a List of Adapters From a Repository Element


If multiple elements match a RanoreXPath of a single repository item use the C reateAdapters method to create a
list of adapters.

C#
view plain c opy to c lipboard print

// Create a list of adapters using the "...Info" object   
IList<Ranorex.Button> buttonList =    
    repo.MyApp.EnabledButtonsInfo.CreateAdapters<Ranorex.Button>();   
  
// Move the mouse pointer to each button of the list   
// and add a screenshot for each to the report             
foreach (Ranorex.Button button in buttonList )   
{   
    button.MoveTo();   
    Report.Screenshot(button);   
}             

VB.NET
view plain c opy to c lipboard print

' Create a list of adapters using the "...Info" object   
Dim buttonList As IList(Of Ranorex.Button) =    
    repo.MyApp.EnabledButtonsInfo.CreateAdapters(Of Ranorex.Button)()   
  
' Move the mouse pointer to each button of the list   
' and add a screenshot for each to the report   
For Each button As Ranorex.Button In buttonList   
    button.MoveTo()   
    Report.Screenshot(button)   
Next  

Learn more about how to create repository items delivering multiple elements here: Adding Repository Items

Using Validate Class


The Ranorex.Validate class is used to check values from UI elements, but it can also be used to simply compare
non UI related objects in code. In comparison to a simple IF statement the methods provided automatically log
fail or sucess messages to the report.

C#
view plain c opy to c lipboard print

// Validate for Existence   
  
// Using 'Info' objects for validation   
// Throws a Ranorex.ValidationException if validation   
// fails. Automatically reports success or failed message   
// to log file                                 
Validate.Exists(repo.SaveDialog.ButtonOKInfo);   
                           
// Validates the existance of the repository item,   
Page 134 of 247
// but does not throw any exception   
bool exists = Validate.Exists(repo.SaveDialog.ButtonOKInfo,"Check Object '{0}'",false);   
               
// Check whether an application form exists using a RanoreXPath   
Validate.Exists("/form[@controlname='formVipApplication']");   
  
// Check whether an application does not exists   
// for the time specified as timeout for the given repository item   
Validate.NotExists(repo.MyApp.SelfInfo);   
  
// Validate 'Enabled' attribute of button 'Delete'   
Validate.Attribute(repo.MyApp.Buttons.ButtonDeleteInfo,"Enabled",false);  

VB.NET
view plain c opy to c lipboard print

  
  
' Validate for Existence   
  
' Using 'Info' objects for validation   
' Throws a Ranorex.ValidationException if validation   
' fails. Automatically reports success or failed message   
' to log file                                  
Validate.Exists(repo.SaveDialog.ButtonOKInfo)   
                           
' Validates the existance of the repository item,   
' but does not throw any exception   
Dim existsn As Boolean = Validate.Exists
(repo.SaveDialog.ButtonOKInfo,"Check Object '{0}'",false)   
               
' Check whether an application form exists using a RanoreXPath   
Validate.Exists("/form[@controlname='formVipApplication']")   
  
' Check whether an application does not exists   
' for the time specified as timeout for the given repository item   
Validate.NotExists(repo.MyApp.SelfInfo)   
  
' Validate 'Enabled' attribute of button 'Delete'   
Validate.Attribute(repo.MyApp.Buttons.ButtonDeleteInfo,"Enabled",false)  

Note: Each method provided by the Validate class allows to suppress exceptions thrown in case of a failed
validation. The code snippet above uses only a few validation methods. For further and more detailed explanation
of the Ranorex.Validate class see the API documention.

Forcing a Test Case to Fail


Ranorex uses exception handling to determine whether a test case run failed or succeeded. As long as no
exception is thrown by any of the Ranorex methods (e.g Ranorex.Validate method or use of not valid repository
item) the test run will be sucessful. If you want to prevent Ranorex from throwing exceptions but at the same
time decide on your own whether a test case fails or not, you need to throw Ranorex exceptions
programmatically.

C#
view plain c opy to c lipboard print

Ranorex.Cell cellObject = null;   
// Try to find  a cell object using two    
// different RanoreXPath expressions   
bool found=false;   
found = Host.Local.TryFindSingle<Ranorex.Cell>("/form//table/row/cell
[3]", 2000, out cellObject);   
found = Host.Local.TryFindSingle<Ranorex.Cell>("/form//table/row/cell
[4]", 2000, out cellObject);   
// If none of the expressions returns an object   
// throw new 'ElementNotFoundException' and test case fails   
if (!found)   
{   
        Ranorex.ElementNotFoundException
Page 135 of 247
    throw new Ranorex.ElementNotFoundException
("Both RanoreXPath with no return", null);                   
}   
else  
{   
    // If the value of attribte 'Text' does not equal to the expected value   
    // throw new 'ValidationException' to break the test case   
    if ( cellObject.Text == "MyExpectedTextValue" )   
    {   
        Report.Success
("User Specific Validation","Text validation of cell object succeeded");   
    }   
    else  
    {   
        throw new Ranorex.ValidationException
("Text validation of cell object succeeded failed");   
    }   
}  

VB.NET
view plain c opy to c lipboard print

Dim cellObject As Ranorex.Cell = Nothing  
' Try to find  a cell object using two    
' different RanoreXPath expressions   
Dim found As Boolean = Host.Local.TryFindSingle(Of Ranorex.Cell)("/form//table/row/cell
[3]", 2000, cellObject)   
found = Host.Local.TryFindSingle(Of Ranorex.Cell)("/form//table/row/cell
[4]", 2000, cellObject)   
' If none of the expressions returns an object   
' throw new 'ElementNotFoundException' and test case fails   
If Not found Then  
    Throw New Ranorex.ElementNotFoundException("Both RanoreXPath with no return", Nothing)
  
Else  
    ' If the value of attribte 'Text' does not equal to the expected value   
    ' throw new 'ValidationException' to break the test case   
    If cellObject.Text = "MyExpectedTextValue" Then  
        Report.Success
("User Specific Validation", "Text validation of cell object succeeded")   
    Else  
        Throw New Ranorex.ValidationException
("Text validation of cell object succeeded failed")   
    End If  
End If  

Set Up Automation Speed


You can optionally specify and change the automation speed at any time in the code. The code generated by a
recording uses the same properties to define replay speed as used within a code module. A newly created code
module already contains three lines of code specifying the automation speed in the 'Run' method.

C#
view plain c opy to c lipboard print

void ITestModule.Run()     
{     
     Mouse.DefaultMoveTime = 300;     
     Keyboard.DefaultKeyPressTime = 100;     
     Delay.SpeedFactor = 1.0;    
}  

VB.NET
view plain c opy to c lipboard print

Page 136 of 247


Private Sub ITestModule_Run() Implements ITestModule.Run   
     Mouse.DefaultMoveTime = 300     
     Keyboard.DefaultKeyPressTime = 100   
     Delay.SpeedFactor = 1.0   
End Sub  

Accessing Test Case & Test Suite Context


Sometimes it's necessary to forward values read from the UI in a code module or recording to the module
executed next in the scope of a test case. The example code shown below uses the parameter 'DialogText' which
is specified within the test case's data binding dialog to transfer data within a test case.

C#
view plain c opy to c lipboard print

  
// ----------------- Code Block used by Code Module A -----------------   
  
// Click 'Save' button to open 'SaveDialog'   
repo.MyApp.Buttons.ButtonSave.Click();   
// Read text message shown with 'SaveDialog'   
// and assign it to test case parameter 'DialogText'   
TestCase.Current.DataContext.Parameters
["DialogText"] = repo.SaveDialog.TextMessage.TextValue;             
  
  
  
// -------- Code Block used by User Code Action of recording B --------               
  
// Read value of 'DialogText' paramaeter in other code module   
// or recording module using a user code action   
Report.Info(TestCase.Current.DataContext.Parameters["DialogText"]);   
  
// Get the current data context and log   
// the current row index of a data driven run   
Report.Info(TestCase.Current.DataContext.CurrentRow.ToString());  

VB.NET
view plain c opy to c lipboard print

  
' ----------------- Code Block used by Code Module A -----------------   
  
' Click 'Save' button to open 'SaveDialog'   
repo.MyApp.Buttons.ButtonSave.Click()   
' Read text message shown with 'SaveDialog'   
' and assign it to test case parameter 'DialogText'   
TestCase.Current.DataContext.Parameters
("DialogText") = repo.SaveDialog.TextMessage.TextValue   
  
  
' Read value of 'DialogText' paramaeter in other code module   
' or recording module using a user code action   
Report.Info(TestCase.Current.DataContext.Parameters("DialogText"))   
  
  
' Get the current data context and log   
' the current row index of a data driven run   
Report.Info(TestCase.Current.DataContext.CurrentRow.ToString())     
  
  
  
' -------- Code Block used by User Code Action of recording B --------               
  
' Read value of 'DialogText' paramaeter in other code module   
' or recording module using a user code action   
Report.Info(TestCase.Current.Parameters("DialogText"))   
  
Page 137 of 247
' Get the current data context and log   
' the current row index of a data driven run   
Report.Info(TestCase.Current.DataContext.CurrentRow.ToString())  

Advanced Code Examples


You can also use RanoreXPath expressions directly in code in order to search for items using different 'Find'
methods offered by the API. Start searching for elements directly at the root level using 'Host.Local' or reuse
existing adapters like repository items to start searching from there.

C#
view plain c opy to c lipboard print

// Create Ranorex.Button adapter using 'FindSingle' method   
// from Host.Local (starting at root node) with absolute RanoreXPath   
// Note: ElementNotFound exception is thrown if item is not found within   
// the specified timeout of 2000 ms.   
Ranorex.Button addButtonVar1 = Host.Local.FindSingle<Ranorex.Button>("/form
[@controlname='formVipApplication']/button[@controlname='btAdd']",2000);   
addButtonVar1.MoveTo();   
               
// Alternatively you can use the 'TryFindSingle' method to prevent   
// a test case from failing  because of an exception thrown if   
// the element is not found within the specified timeout of 2000 ms   
Ranorex.Button addButtonVar2 = null;   
bool found = Host.Local.TryFindSingle<Ranorex.Button>("/form
[@controlname='formVipApplication']/button
[@controlname='btAdd']", 2000, out addButtonVar2);   
// Move mouse pointer to button   
addButtonVar2.MoveTo();   
                           
// Request a list of buttons shown from the VIP Database application   
// and create a screenshot for each button in the report file   
IList<Ranorex.Button> buttonList = Host.Local.Find<Ranorex.Button>("/form
[@controlname='formVipApplication']/button",500);   
foreach (Ranorex.Button bt in buttonList)   
{   
     Report.Screenshot(bt);   
}   
  
// Using find methods in combination with existing Ranorex repository items   
Ranorex.Button btAdd = repo.MyApp.Self.FindSingle<Ranorex.Button>("button
[@controlname='btAdd']",2000);  

VB.NET
view plain c opy to c lipboard print

' Create Ranorex.Button adapter using 'FindSingle' method   
' from Host.Local (starting at root node) with absolute RanoreXPath   
' Note: ElementNotFound exception is thrown if item is not found within   
' the specified timeout of 2000 ms.   
Dim addButtonVar1 As Ranorex.Button = Host.Local.FindSingle(Of Ranorex.Button)("/form
[@controlname='formVipApplication']/button[@controlname='btAdd']", 2000)   
addButtonVar1.MoveTo()   
  
' Alternatively you can use 'TryFindSingle' method to prevent   
' a test case from failing  because of an exception thrown if   
' the element is not found within the specified timeout of 2000 ms   
Dim addButtonVar2 As Ranorex.Button = Nothing  
Dim found As Boolean = Host.Local.TryFindSingle(Of Ranorex.Button)("/form
[@controlname='formVipApplication']/button[@controlname='btAdd']", 2000, addButtonVar2)   
' Move mouse pointer to button   
addButtonVar2.MoveTo()   
  
' Request a list of buttons from the VIP Database application   
' and create a screenshot for each button in the report file   
Dim buttonList As IList(Of Ranorex.Button) = Host.Local.Find(Of Ranorex.Button)("/form
[@controlname='formVipApplication']/button", 500)   
Page 138 of 247
For Each bt As Ranorex.Button In buttonList   
    Report.Screenshot(bt)   
Next  
  
' Using find methods in combination with existing Ranorex repository items   
Dim btAdd As Ranorex.Button = repo.MyApp.Self.FindSingle(Of Ranorex.Button)("button
[@controlname='btAdd']", 2000)  

How to do image based automation


If Ranorex is not able to clearly identify some of your GUI elements, it may be helpful to automate them using
the implicit image search mechanism of the 'C lick' method.

C#
view plain c opy to c lipboard print

// Create bitmap to search for   
// within application form and   
// click it   
Bitmap bmp = Ranorex.Imaging.Load(   
                       @"..\..\Green Sea Turtle Small.bmp");               
// Performs a right click on the image found   
// within the application window based on   
// the image location   
myRepo.WinFormsApp.Self.Click(MouseButtons.Right,bmp);   
  
// You can also search for images that are slightly different to the   
// loaded image by specifying the minimum Similarity for a match (95% = 0.95).   
myRepo.WinFormsApp.Self.Click(new Location(bmp, new Imaging.FindOptions(0.95)));   
               
// OR Set the default Similarity value for all following image operations   
Imaging.FindOptions.Default.Similarity = 0.95;   
myRepo.WinFormsApp.Self.Click(bmp);   
               
Report.Success("Image found and clicked successfully");  

VB.NET
view plain c opy to c lipboard print

' Create bitmap to search for   
' within application form and   
' click it   
Dim bmp As Bitmap = Ranorex.Imaging.Load("..\..\Green Sea Turtle Small.bmp")   
' Performs a right click on the image found   
' within the application window based    
' on the image location   
myRepo.WinFormsApp.Self.Click(MouseButtons.Right, bmp)   
  
' You can also search for images that are slightly different to the   
' loaded image by specifying the minimum Similarity for a match (95% = 0.95).   
myRepo.WinFormsApp.Self.Click(new Location(bmp, new Imaging.FindOptions(0.95)))   
               
' OR Set the default Similarity value for all following image operations   
Imaging.FindOptions.Default.Similarity = 0.95   
myRepo.WinFormsApp.Self.Click(bmp)   
  
Report.Success("Image displayed successfully")  

How to find and compare images


To compare an image simply search for it within an existing Ranorex element using the 'C ontains' method.

C#

Page 139 of 247


view plain c opy to c lipboard print

// Create bitmap   
Bitmap bmp = Ranorex.Imaging.Load(   
                       @"..\..\Green Sea Turtle Small.bmp");               
                   
// Search for it within the application window   
if (Ranorex.Imaging.Contains(myRepo.WinFormsApp.Self,bmp) == true)   
{   
  Report.Success("Image found within WinForms application");   
}  

VB.NET
view plain c opy to c lipboard print

' Create bitmap   
Dim bmp As Bitmap = Ranorex.Imaging.Load("..\..\Green Sea Turtle Small.bmp")   
' Search for it within the application window   
If Imaging.Contains(myRepo.WinFormsApp.Self,bmp Then  
  Report.Success("Image found within WinForms application")   
End If  
    

Note: Both examples load an uncompressed file (BMP or PNG format) in order to carry out a one-to-one
comparison. Use the FindOptions class to configure similarity, preprocessing and other search settings.

Handling Unexpected Dialogs


The following code iterates through a Win32 tree control well known from windows file explorer using the
TreeView class.

Folder options dialog

Page 140 of 247


Warning dialog which has to be handled during test

C#
view plain c opy to c lipboard print

Form optionsDialog = "/form[@title='Folder Options']";   
Tree settingsTree = optionsDialog.FindSingle<Ranorex.Tree>   
                        ("container[@caption='View']/tree[@controlid='30120']");   
foreach (TreeItem item in settingsTree.Items)   
{   
  IterateTree(item);   
}   
  
static void IterateTree(Ranorex.TreeItem treeItem)   
{   
   foreach (Ranorex.TreeItem item in treeItem.Items)   
   {   
     item.Click();                   
     CheckForWarningDialog();   
  
     Thread.Sleep(100);   
     if (item.Items.Count > 0)   
     {   
       IterateTree(item);   
     }   
  
     item.Click();   
     CheckForWarningDialog();                   
  }   
}   
  
// Some mouse clicks causes a warning dialog to popup   
// which has to be handled and closed   
static void CheckForWarningDialog()   
{   
   Ranorex.Button button=null;   
   if (Host.Local.TryFindSingle("/form[@title='Warning']/button
[@text='&No']", 1000, out button))   
      button.Click();   
}  

VB.NET
view plain c opy to c lipboard print

Dim optionsDialog As Form = "/form[@title='Folder Options']"  
Dim settingsTree As Tree = optionsDialog.FindSingle(Of Ranorex.Tree)("container
[@caption='View']/tree[@controlid='30120']")   
For Each item As TreeItem In settingsTree.Items   
  IterateTree(item)   
Next  
  
  
Private Shared Sub IterateTree(treeItem As Ranorex.TreeItem)   
  For Each item As Ranorex.TreeItem In treeItem.Items   
    item.Click()   
    CheckForWarningDialog()   
  
    Thread.Sleep(100)   
    If item.Items.Count > 0 Then  
      IterateTree(item)   
    End If  
  
Page 141 of 247
    item.Click()   
    CheckForWarningDialog()   
  Next  
End Sub  
  
' Some mouse clicks causes a warning dialog to popup   
' which has to be handled and closed   
Private Shared Sub CheckForWarningDialog()   
  Dim button As Ranorex.Button = Nothing  
  If Host.Local.TryFindSingle("/form[@title='Warning']/button
[@text='&No']", 1000, button) Then  
    button.Click()   
  End If  
End Sub  

C opyright © 2012 Ranorex

Page 142 of 247


Data Connectors
In this section you learn about how to define different types of external data sources to be used for test
automation.

Simple Data Table


C SV File
SQL C onnector
Excel File

Manage Data Sources


There are two locations on which you can manage data sources, one for the whole test suite and one for a
specific test case. To maintain all data connectors in your test suite, open the data source management dialog by
pressing the “Manage Data Sources…” button.

Open 'Manage Data Sources' dialog from test suite


view

'Manage Data Sources' dialog

In this dialog you can add new data connectors of the types described in the next chapters and rename or delete
existing data connectors.

To add an existing data connector or create a new data connector to one of your test cases, select the desired
test case from test suite view and open the data source dialog by pressing the “Data Source…” button.

Page 143 of 247


Set up data sources for a test case

Test case properties dialog shows the currently


used data source

In this new opened dialog you can create a new data connector by selecting one of the data connector types
described in the next chapters from the combo box marked in green. You can also choose an existing data
connector by selecting one of the data sources from the combo box marked in red. By pressing the blue marked
button, labeled “Manage Data Sources” the data source management dialog, explained before, will be opened. By
pressing the yellow marked button labeled “Refresh”, the data of the actual selected data source will be updated
from its source file or database. You can limit the data of your data source by selecting a data range in the area
marked orange. To open a dialog showing you the effective data set limited by a range (area marked in orange),
press the purple marked button, labeled “Preview effective data set…”.

Preview the effective data set

In this dialog you can update the effective data set from the data file or database by pressing the green marked
button labeled “Refresh”. You can also export the effective data set to a C SV file by pressing the red marked
button, labeled “Export C SV”.

Kind of Data Connectors


In the following chapters you will learn how to create the different types of data connectors and add them to an
existing test case. To do so, select the desired test case and open the data source dialog as described in General
Use of Data C onnectors. In this dialog choose one of the following data connector types from the combo box
labeled “New”.
Page 144 of 247
Simple Data Table
C SV File
SQL C onnector
Excel File

C opyright © 2012 Ranorex

Page 145 of 247


Simple Data Table
This Data C onnector allows you to easily generate a data table. After adding this type of data connector you can
enter a name for the data table by clicking on the blue area and adding a text value and add new columns and
rows by clicking on either the red marked area for columns or the green marked area for rows and adding a text
value.

Add new test data directly to a table of type 'Simple


Data Connector'

C opyright © 2012 Ranorex

Page 146 of 247


CSV File
You can also use a C SV file to provide data for your test suite by choosing this type of data connector. After
adding a C SV file data connector, the data source management dialog will be opened.

You can edit the name of the data connector in the text box marked in red and choose the C SV file by selecting a
file in the green marked area. By checking or un-checking the check box marked blue you can decide either to
include or to exclude the selected C SV file to your test suite. By checking this check box, a copy of the file will be
placed in your solutions folder. By checking the yellow marked check box, the first line of your C SV file will be
added as the header of all rows.

Set up CSV file as external data source

C SV data connectors are, like simple data connectors, not read-only. You can add rows and columns in the same
way as described in chapter Simple Data Table. The changes to your table will be applied to the C SV file. If you
have chosen the option 'Include File in Test Suite' in the data source management dialog, the changes will be
applied to the local copy of your C SV file.

C opyright © 2012 Ranorex

Page 147 of 247


SQL Connector
The third type of data connector is the SQL connector. This connector allows you to access a SQL database and
get the desired data using a SQL query. After adding a SQL connector, the data source management dialog will
be opened.

You can edit the name of the data connector in the text box marked yellow. To generate a connection string to
connect to your database, press the red marked 'C reate' button. After establishing a connection to the database
by generating a connection string, you can add an SQL query by pressing the green marked 'C reate' button.

Set up SQL connector - main dialog

Create Connection String


By pressing the red marked 'C reate' button in the data source management dialog the connection properties
dialog will be opened.

SQL connector - Connection Properties dialog

Page 148 of 247


The appearance of this dialog depends on the data source which can be chosen by pressing the 'C hange' button
marked red. In this screenshot, a 'Microsoft Access Database File' is chosen as data source. You can choose the
database file by pressing the 'Browse' button marked green and set the user name and the password in the area
marked yellow. But as explained before, the kind and number of properties will depend on the chosen data
source. By pressing the orange marked button labeled 'Advanced…' the advanced property dialog will be opened.
In this dialog you can edit the advanced options of your database connection. After configuring all relevant
options, you can check if the database connection is working by pressing the purple marked button labeled 'Test
C onnection'.

Create Query
By pressing the green marked 'C reate' button in the data source management dialog the query design dialog will
be opened.

SQL Query Designer used to create SQL queries

You can add a column by double clicking an attribute of a table in your database. These attributes can be found in
the area marked green. These attributes will be added to the area marked red, keeping the column headings
shown in your data connector, as well as in the area marked blue, with the SQL query. Pressing the button
marked yellow will add a 'GROUP BY' statement to the SQL query. Pressing the button marked orange will allow
you to add advanced settings to your SQL query. Pressing the purple button will check SQL syntax. Pressing the
light blue button will show you a preview of the data set retrieved by the SQL query. Pressing the button marked
brown will reset the SQL query.

C opyright © 2012 Ranorex

Page 149 of 247


Excel File
The last type of data connector is the Excel file connector. This connector allows you to use an Excel file to
provide data for your test suite. After adding an Excel file connector, the data source management dialog will be
opened.

You can edit the name of the data connector in the text box marked red and choose the Excel file by selecting a
file in the green marked area. By checking or un-checking the check box marked blue you can decide either to
include or to exclude the selected Excel file to your test suite. By checking this check box, a copy of the file will
be placed in your solutions folder. Additionally you can define the worksheet and the range of the worksheet
which will provide the data for the Excel file connector in the yellow marked area.

Create new Excel file connector

C opyright © 2012 Ranorex

Page 150 of 247


Instrumentation Wizard
Ranorex supports the testing of many different UI technologies, however some technologies need
to be instrumented correctly to guarantee the best possible automation results. The Ranorex
Instrumentation Wizard is a tool which helps you instrumenting these technologies to ensure optimal object
recognition and consequently robust test automation projects.

The Ranorex Instrumentation Wizard can be started either from “Tools” menu in Ranorex Studio, from the pop-up
dialog triggered by a technology limitation, from the start menu, or directly from the binary folder of your
Ranorex installation (<Ranorex Installation Folder>\bin\Ranorex.InstrumentationWizard.exe). When starting the
Wizard from the “bin” folder of your Ranorex installation, you have to make sure to start the executable with
administrator rights.

The wizard is used to instrument the following technologies:

Java AWT/Swing
Adobe Flash/Flex
Mozilla Firefox
Google C hrome
Apple Safari
Android

Start Instrumentation Wizard from


Ranorex Tools Menu

Start Instrumentation Wizard from Technology


Limitation

Page 151 of 247


Start Instrumentation Wizard from Start
Menu

By starting the wizard from the “Tools” menu, from the start menu or from the “bin” folder, you can choose which
kind of technology you want to instrument, whereas the technology limitation pop-up leads you directly to the
instrumentation of the technology with limited identification capabilities.

Instrumentation Wizard

C opyright © 2012 Ranorex

Page 152 of 247


Java AWT/Swing
The Java AWT/Swing technology limitation will pop up if your Java installation or application is not instrumented
correctly.

Java AWT/Swing Technology Limitation

The Instrumentation Wizard tries to add the Plug-In specific files to the Java Runtime Environment (JRE) of your
choice and to activate the Java Plug-In for Ranorex.

You have 3 different choices:

Select a JRE from a list of running Java applications: Here you can choose the Java runtime based
on the application you want to instrument. This is the preferred method, as you can determine exactly
which Java runtime is being used by your application under test.

Select a JRE from a list of installed Java runtimes: Here you can choose the Java Runtime
Environment you want to be instrumented from a list of all installed Java runtimes on your machine.

Specify a custom Java runtime directory: Here you can specify the folder holding the Java runtime
you want to be instrumented.

Java Instrumentation Wizard

After activating the Java AWT/Swing instrumentation, Ranorex will not be limited in recognizing UI elements of
your Java application. Restart your application under test and your Ranorex tools to ensure that the newly added
instrumentation works correctly.

Page 153 of 247


Finished Java Instrumentation

If you are using Windows XP SP2, please also make sure that the Windows Update KB884020 is installed, which
resolves problems with the local network communication.

If the activation of the Java Plug-In was not successful, please make sure that you have installed Ranorex
correctly, that you have chosen the right directory of your JRE, and if you have started the Instrumentation
Wizard from the “bin” folder that it has been started with admin rights.

Failed Java Instrumentation

C opyright © 2012 Ranorex

Page 154 of 247


Adobe Flash/Flex
The Flash/Flex technology limitation will pop up if your Flash/Flex application is not instrumented
correctly.

Flash/Flex Technology Limitation

Note: If you need to automate an Adobe AIR application, please read how to do the instrumentation manually for
Adobe AIR testing chapter.

The instrumentation Wizard tries to install either the Flash Debug Player for Internet Explorer or
the Flash Debug Player for Mozilla Firefox, Google Chrome and Safari or both Flash Debug Players if
you like.

Moreover, you can enable the Ranorex Preloader Instrumentation. This allows you – in combination with the Flash
Debug Player – to instrument your application under test without the need to alter your application.

Additionally, you can enable logging for the Flash Debug Player. This might be helpful if you have any problems
with this kind of instrumentation. In such case you can then simply provide this logging information to our support
team.

After installing the Debug Players and activating the Ranorex Preloader, Ranorex should be able to recognize
your Flash and Flex applications without any limitations. Restart your application under test and your Ranorex
tools to ensure that the newly added instrumentation works correctly.

Page 155 of 247


Finished Flash/Flex Instrumentation

If you still have problems within recognition of Flash/Flex applications, please make sure that your applications
are not double instrumented, i.e. make sure that you do not use any Ranorex Library or Ranorex Module within
your Flash/Flex application.

Google Chrome
To use the preloader method with Google C hrome, you have to disable the internal Flash Player.
This can be done by performing following steps:

Open C hrome's plugins overview (chrome://plugins/):

Display the Plug-Ins details:

Disable the internal Flash Player (framed red) and keep the Flash Debug Player (framed green) enabled:

Page 156 of 247


C opyright © 2012 Ranorex

Page 157 of 247


Mozilla Firefox
The Mozilla technology limitation will pop up if the Ranorex Add-On for you Mozilla Browser is not installed or
enabled. This technology limitation should only occur if you install Firefox after successfully installing Ranorex. If
Mozilla Firefox has been installed before installing Ranorex, the Mozilla Browser Add-On will be installed and
activated automatically.

Mozilla Firefox Technology Limitation

The Instrumentation Wizard tries to install the Mozilla Firefox Add-On when checking the checkbox “Activate
Mozilla Firefox Add-On” and tries to uninstall the Add-On when unchecking the mentioned checkbox.

Mozilla Firefox Instrumentation Wizard

After installing the Add-On, Ranorex should not have any limitation recognizing UI elements within your web
document. Restart your application under test and your Ranorex tools to ensure that the newly added
instrumentation works correctly.

Finished Mozilla Firefox Instrumentation

If the activation of the Add-On was not successful, please make sure that you have installed Ranorex correctly
and if you have started the Instrumentation Wizard from “bin” folder that it has been started with admin rights.

Page 158 of 247


Failed Mozilla Firefox Instrumentation

If you still get a limitation when tracking web elements, please assure that the Mozilla Firefox Add-On is enabled
in the Firefox Add-On settings.

Note: To successfully activate the Ranorex Add On for Firefox 8 and greater, it is necessary to confirm its
installation.

Confirm Ranorex Automation Add-On installation

C opyright © 2012 Ranorex

Page 159 of 247


Google Chrome
The C hrome technology limitation will pop up if the Ranorex Extension for the C hrome Browser is not installed or
enabled.

Google Chrome Technology Limitation

The Instrumentation Wizard tries to activate the Google C hrome Extension when checking the checkbox “Activate
Google C hrome Addon” and tries to deactivate the Extension when unchecking the mentioned checkbox.

Google Chrome Instrumentation Wizard

After activating the Extension, Ranorex should not have any limitation recognizing UI elements within your web
document. Restart your application under test and your Ranorex tools to ensure that the newly added
instrumentation works correctly.

Finished Google Chrome Instrumentation

If the activation of the Add-On was not successful, please make sure that you have installed Ranorex correctly
and if you have started the Instrumentation Wizard from “bin” folder that it has been started with admin rights.

Page 160 of 247


Failed Google Chrome Instrumentation

If you still get a limitation when tracking web elements, please assure that the Ranorex Automation Extension is
enabled in the C hrome Extensions settings (chrome://settings/extensionSettings).

Enable Ranorex Automation Extension

If you have removed the Ranorex Automation Extension manually, you have to manually re-add the Extension.
Therefore you have to open the file RanorexAutomation.crx, which can be found in the binary folder of your
Ranorex installation ('..\Ranorex 3.2\bin\ RanorexAutomation.crx '), in C hrome and install by following the
instructions.

Install Ranorex Automation Extension manually

Note: If you want to test cross domain iframe scripting with Google C hrome, you have to start C hrome with the
command line argument “--disable-web-security”.

Note: If you want to test file URLs, you have to enable “Allow access to file URLs” for the Ranorex Automation
Extension.

Allow access to file URLs

Note: if the NotScript C hrome Extension is installed it has to be disabled to allow from point tracking with
Ranorex.

C opyright © 2012 Ranorex

Page 161 of 247


Apple Safari
The Safari technology limitation will pop up if the Ranorex Extension for the Safari Browser is not installed or
enabled.

Apple Safari Technology Limitation

The Instrumentation Wizard tries to activate the Safari Extension when checking the checkbox “Activate Apple
Safari Addon” and tries to deactivate the Extension when unchecking the mentioned checkbox.

Apple Safari Instrumentation Wizard

After activating the Extension, you have to confirm the installation in Safari.

Confirm installation of Ranorex Automation


Extension

After activating the Extension and confirming the installation, Ranorex should not have any limitation recognizing
UI elements within your web document. Restart your application under test and your Ranorex tools to ensure that
the newly added instrumentation works correctly.

Page 162 of 247


Finished Apple Safari Instrumentation

If the activation of the Extension was not successful, please make sure that you have installed Ranorex correctly
and if you have started the Instrumentation Wizard from “bin” folder that it has been started with admin rights.

Failed Apple Safari Instrumentation

If you still get a limitation when tracking web elements, please assure that the Apple Safari Extension is enabled
in the Safari Extensions settings (Preferences->Extensions).

Enable Ranorex Automation Extension

Note: Testing file URLs with Apple Safari is currently not supported.

Note: Testing cross domain iframe scripting with Apple Safari is currently not supported.

C opyright © 2012 Ranorex

Page 163 of 247


Android
To make an Android app automatable by Ranorex, it is necessary to instrument this application using the
Instrumentation wizard.

Note: Have a look at Android Testing - Getting Started to learn how to automate Android applications.

Android instrumentation wizard

C hoose the APK file of the app and the device, the instrumented APK file will be deployed to. More information
about setting up a mobile device can be found in section Manage Devices.

If the APK is already instrumented and only needs to be deployed on a mobile device, the checkbox “Instrument
the APK under test before deployment” can be unchecked.

After processing the instrumentation and deploying the instrumented APK file to the selected device, the
installation has to be confirmed on the device.

Finished Android instrumentation

The instrumented APK file can be found at location referenced by the link “Open instrumentation File location”.

After instrumenting the APK file, the app is available in the “Mobile Recording” section of Record Setting dialog.

Page 164 of 247


nstrumented APK in Record Settings

The Ranorex Service App installed on the mobile device shows an overview of instrumented apps installed on the
device.

Overview of instrumented
APKs

C opyright © 2012 Ranorex

Page 165 of 247


Working with 2.X Projects in 3.X Test Suites
In this section you will learn how to use your 2.X recordings and code modules in Ranorex 3.X test cases within
the new test suite editor.

Adding 2.X Projects to 3.X Projects


Using 2.X Recording Modules
Adapting 2.X Data-Driven Recording Modules
Using 2.X C ode Modules
Breaking C hanges

Adding 2.X Projects to 3.X Projects


Ranorex 2.X projects are fully compatible (except for the following breaking changes) and can therefore be used
within Ranorex 3.X test solutions.

1. Create or open a Ranorex Test Suite Project


In order to use your existing modules within a test suite, it is required to create a new test suite project.

Lesson 1: Getting Started with Ranorex 3.X

2. Make a backup of your existing 2.X project and add it to the Test Suite Project

3. Confirm that you want to convert your old project

Using 2.X Recording Modules


Now you are ready to reuse your existing recording modules. You can simply drag and drop items from the
module browser into your test cases or you can add new or existing items using the context menu as follows:

Page 166 of 247


Add an existing recording module

Adapting 2.X Data-Driven Recording Modules


The new Ranorex Recorder allows you to add variables without having to write a line of code. The variables can
then be bound to action item properties or can be used within a RanoreXPath expression. Please see following
section for more information: Lesson 3: Data-Driven Testing

You can easily adapt your existing data-driven test recording modules by doing following:

1. Open your recording file and click on the "Variables..." button in the Ranorex Recorder view

2. Add all variables used in your code

3. Open the UserCode file of your recording and remove your existing properties

4. Remove the 'static' keyword from your UserCode methods 


Now you are able to bind your module variables to a data column or parameter within a test case.

Using 2.X Code Modules


Page 167 of 247
In order to call your existing test methods within the Ranorex test suite editor we recommend to add a code
module to your project as follows:

1. Select your project in the projects view and click on "Add Code Module"

Add a new code module

2. Call your method by adding it to the end of the "ITestModule.Run()" method

C#
view plain c opy to c lipboard print

namespace MyFirstTestProject   
{   
    /// <summary>   
    /// Description of AddAndDeleteVip.   
    /// </summary>   
    [TestModule("A730AB98-9CFE-49D5-BDA7-0CAE6C614866")]   
    public class AddAndDeleteVip : ITestModule   
    {   
        public AddAndDeleteVip()   
        {   
        }   
       
        void ITestModule.Run()   
        {   
            Mouse.DefaultMoveTime = 300;   
            Keyboard.DefaultKeyPressTime = 100;   
            Delay.SpeedFactor = 1.0;   
  
            // Call your existing test method   
            Program.ExistingTest();   
        }   
    }   
}  

Now you can add your code module to a test case. Please see following pages for more information about code
modules:

C reating C ode Module


Using Repository within C ode Module
Using Variables with C ode Modules
Using C ode Modules within Test C ases

Breaking Changes
A few changes had to be introduced that can break existing Ranorex 2.X projects when updating to Ranorex 3.X.
If your automation project does not work any more after updating to 3.X, please see the following list that
explains what has changed and how you need to update your project to make it work with 3.X again:

The Delay class has been moved from the "Ranorex.C ore" to the "Ranorex" namespace. If the Delay class
cannot be found, you need to include the "Ranorex" namespace at the top of the file:

C#
Page 168 of 247
view plain c opy to c lipboard print

using Ranorex;  

VB.NET
view plain c opy to c lipboard print

imports Ranorex  

The IReportLogger interface has been extended. In particular, the signature of the LogText and LogData
methods changed and the PreFilterMessages property was added. If you get compile errors after updating
stating that your classes do not correctly implement the IReportLogger interface, please update the
implementing classes accordingly. See following blog on how to implement the new IReportLogger
interface:
C ustomizing Ranorex Reports
The tree structure for MSAA elements has changed under certain circumstances and potentially includes
more levels and elements now. If you do not want to use the new elements, set the MSAA "Filter
compatibility level" setting in the "Plugins" tab of the Ranorex settings to "V2X". Otherwise, please, update
broken RanoreXPaths accordingly.
Text nodes which consist only of white-spaces are no longer appended to Mozilla WebElement.InnerText.
Please, update RanoreXPaths and validations that depend on this property and fail accordingly.
Some Win32 controls in the tree no longer have the role Form, but a more appropriate role instead. If you
want Ranorex to not use the new role, set the Win32 "Use legacy Form role" setting in the "Plugins" tab of
the Ranorex settings to "True". Otherwise, please, update broken RanoreXPaths accordingly.
C ontrol.Get/SetPropertyValue now use Reflection instead of the C omponentModel. If a property cannot be
found, please check that the used name correctly reflects the API name of the property.
The C ontrolNet11 capability is no longer used as the preferred capability for .NET 1.1 controls. As a
consequence, the generated path to items with that capability can change (existing paths will still work).
With version 3.0.1 Ranorex added basic support for Delphi controls resulting into different RanoreXPaths
being generated for many Delphi controls. If you do not want to use the new functionality, set the Win32
"Enable basic Delphi support" setting in the "Plugins" tab of the Ranorex settings to "False".

C opyright © 2012 Ranorex

Page 169 of 247


Technology Instrumentation
Ranorex supports testing of many different UI technologies. Although some of them need to be instrumented
correctly to ensure optimal object recognition and furthermore to built robust test automation projects. If an
application under test requires additional manual instrumentation, a pop-up dialog is shown when using a Ranorex
tool.

Technology limitation box shown for not


instrumented application

Learn more about technology dependent instrumentation and how to troubleshoot object recognition issues using
the information below:

Flash/Flex Testing
Testing of Java Applications
Qt Testing
Testing of Legacy Applications
General Troubleshooting

C opyright © 2012 Ranorex

Page 170 of 247


Flash/Flex Testing
The Flash/Flex Test Automation Plugin provides a smooth integration with the Ranorex Automation Framework and its
tools. You can easily filter, access and validate Flex controls easily using RanoreXPath. You have full access to all the
properties and attributes of Flash and Flex elements.

Prerequisites Samples
The automation of Flash/Flex applications A flash/flex test sample project is included
requires inclusion of the Ranorex Flex with the Ranorex installation package
Automation Lib. (shown on the startpage of Ranorex
Studio).
Using the Ranorex PreLoader
How to read/set attributes and
styles
OR including the Ranorex Lib
into Adobe Flex: How to load the
Ranorex Lib into a Flex application

into Adobe Flash: How to load the


Ranorex Lib into a Flash application

Methods for loading the Automation Lib


Depending on your flash/flex application, you can choose to use one of the following flexible instrumentation methods:

PreLoader (recommended)
The Ranorex PreLoader enables automation of your flash/flex application without modifying the application itself.

Automatic installation using the Instrumentation Wizard


No modifications to your application needed
Adobe Flash Debug Player has to be installed on the runtime machine

Automation Lib
The AutomationLib swc file has to be included into your flash/flex application (by adding a compiler argument).

AutomationLib will be loaded in background (will not affect the functionality of your flash/flex application)
No modifications to your website needed

Module
The Module swf file has to be loaded by adding a code snippet to your AC TIONS (for flash) or to your
"applicationC ompleteHandler" function (for flex).

Module will be loaded in background (will not affect the functionality of your flash/flex application)
No modifications to your website needed
Module swf has to be copied to the web server

The following table shows you the different instrumentation options available for the supported versions of flash/flex ( =
supported, = recommended):

Flash Flex AIR*

CS3 CS4 CS5 3.X 4.X 2.X

Page 171 of 247


PreLoader

Automation Lib

Module

* Support for Adobe AIR 2 Release in combination with Flex 3.5 and Flex 4 Release

Test Automation of Flash/Flex controls with Ranorex


The architecture of a Flash/Flex object is easy to see within Ranorex Spy. All embedded Flash or Flex elements are shown
as a Flex element in the tree view.

Use Ranorex Recorder to automate Flash/Flex applications in all supported browser (Internet Explorer, Firefox, C hrome
and Safari). You can add user code actions to your recordings to access custom Flex properties.

How to read/set attributes and styles


You can read/set common attributes (e.g. the checkstate of a checkbox) directly by using the adaptor as follows:

view plain c opy to c lipboard print

// Set the checked state with the property "Checked"   
repo.FlexTestPageDom.CheckBox_Control_Example.CheckBoxEggs.Checked = true;  

To access custom attributes and styles, you first have to load your Flex item as a FlexElement in order to read your
attributes. Here's an example:

view plain c opy to c lipboard print 5


// Load the slider as a Flex element to access flex attributes   
FlexElement sliderFlex = repo.FlexTestPageDom.ContainerHSlider_Control.SliderHSlider.As<FlexElement>
();   
sliderFlex["value"] = "100";   
  
FlexElement containerFlex = repo.FlexTestPageDom.Self.FindSingle(".//container
[@caption='Tree Control']");    6
3 4

Using the Ranorex PreLoader


Please use the Instrumentation Wizard to enable the PreLoader method on your machine.

Page 172 of 247


The wizard will execute following steps for you:

1. Install the Adobe Debug Flash Player on the machine on which you would like to record and execute Ranorex
test scripts and for all browsers you would like to test with. The installers are available on Adobe’s download page;
the following are the links to the Debug Player for Internet Explorer and Firefox/C hrome/Safari.
2. Open your user profile directory %UserProfile%, e.g. by opening Windows Explorer and copying the string %
UserProfile% into the address bar.
3. Create a new file called „mm.cfg” in your user profile directory and insert the following line of code, where
“C :\FlashFlex\RanorexAutomation.swf” needs to be replaced by the preloader location of your Ranorex installation:
PreloadSwf= C:\Program Files\Ranorex 3.X\Bin\RanorexAutomation.swf
Additional to this configuration entry you can enable the logging mechanisms of the Adobe Debug Flash Player,
which might be helpful if you have any problems with this kind of instrumentation. In such a case you can then
simply provide this logging information to our support team. To enable logging you have to add the following line of
code to your “mm.cfg” file:

TraceOutputFileEnable=1
This additional configuration entry forces the Debug Player to create a log file at following location:
C :\Users\username\AppData\Roaming\Macromedia\Flash Player\Logs

4. If you run your application from the local drive, add your output directory to the trusted locations of Flash Player as
follows:
1. Open following link
http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html#119065
2. Add your project output directory

Adobe Flex: Load the Ranorex Lib into your Flex application

1. Start Adobe Flex Builder and open your workspace


2. Right-click on your project and choose Properties
3. Under Flex C ompiler add the RanorexAutomation.swc file (located in the Bin directory of your Ranorex
installation) to the the compiler argument as follows:

view plain c opy to c lipboard print

-include-libraries "C:\Program Files\Ranorex 3.X\Bin\RanorexAutomation.swc"  

4. For AIR2: Append following code to your "applicationC ompleteHandler" function:

view plain c opy to c lipboard print

import Ranorex.RxAutomation;      
RxAutomation.Init();    

5. Save and compile your application


6. Run your application in a supported browser (Internet Explorer, Firefox, C hrome, Safari)
7. If you run your Flex application from the local drive, add your output directory to the trusted locations of Flash
Player as follows:
1. Open following link
http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html#119065
2. Add your project output directory

Adobe Flash: Load the Ranorex Lib into your Flash application

1. Start Adobe Flash C S4/C S5 and open your application


Page 173 of 247
2. Open the "Publish Settings" dialog (File->Publish Settings)
3. Include the Ranorex Flash Library in your Flash application under Flash->Script->Settings...->Library Path and
choose "Browse to SWC file"
4. Select "RanorexAutomation.swc" file in the browse dialog (RanorexAutomation.swc is located in the Bin directory of
your Ranorex installation)
5. Insert following code to your AC TIONS (by pressing F9):

view plain c opy to c lipboard print

import Ranorex.RxAutomation;    
RxAutomation.InitFromApp(stage);  

OR add the code to your ActionScript source file as follows:

view plain c opy to c lipboard print

import mx.controls.*;   
import flash.events.*;   
import flash.display.*;   
import flash.ui.Keyboard;   
import flash.geom.Rectangle;   
import fl.events.SliderEvent;   
// Add Ranorex library   
import Ranorex.RxAutomation;   
  
public class Simple extends MovieClip   
{   
    public function Simple()   
    {   
        // Add to your constructor   
        RxAutomation.InitFromApp(stage);   
    }   
}  

6. Run your application in a supported browser (Internet Explorer, Firefox, C hrome, Safari)
7. If you run your Flash application from the local drive, add your output directory to the trusted locations of Flash
Player as follows:
1. Open following link
http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html#119065
2. Add your project output directory

How to load the Ranorex Module into your Flash application

1. Start Adobe Flash C S3/C S4/C S5 and open your application


2. Insert following code to your AC TIONS (by pressing F9):

view plain c opy to c lipboard print

import flash.net.URLRequest;   
var rxloader : Loader = new Loader();   
stage.addChild(rxloader);   
rxloader.name = "__rxloader";   
rxloader.width = 0; rxloader.height = 0;   
rxloader.load(new URLRequest("RanorexAutomation.swf"));  

3. C opy the RanorexAutomation.swf file, located in the Bin directory of your Ranorex installation, to your web
server (where your .swf file is located)
4. Run your application in a supported browser (Internet Explorer, Firefox, C hrome, Safari)
5. If you run your Flash application from the local drive, add your output directory to the trusted locations of Flash
Player as follows:
1. Open following link
www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html
2. Add your project output directory

How to load the Ranorex Module into your Flex/AIR application

1. Start Adobe Flex Builder or Flash Builder and open your workspace
2. Append following code to your "applicationC ompleteHandler" function or initialization code:
For Flex 3:

view plain c opy to c lipboard print

Page 174 of 247


var rxloader : Loader = new Loader();   
Application.application.rawChildren.addChild(rxloader);   
rxloader.name = "__rxloader";   
rxloader.width = 0; rxloader.height = 0;   
rxloader.load(new URLRequest("RanorexAutomation.swf"));  

For Flex 4:

view plain c opy to c lipboard print

var rxloader : Loader = new Loader();   
FlexGlobals.topLevelApplication.parent.addChild(rxloader);   
rxloader.name = "__rxloader";   
rxloader.width = 0; rxloader.height = 0;   
rxloader.load(new URLRequest("RanorexAutomation.swf"));  

3. C opy the RanorexAutomation.swf file, located in the Bin directory of your Ranorex installation, to your web
server (where your .swf file is located) or where your AIR application is located.
4. Run your application in a supported browser (Internet Explorer, Firefox, C hrome, Safari)
5. If you run your Flash application from the local drive, add your output directory to the trusted locations of Flash
Player as follows:
1. Open following link
www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html
2. Add your project output directory

C opyright © 2012 Ranorex

Page 175 of 247


Testing of Java Applications
The Ranorex Java Plug-In allows testing of Java Swing and Java AWT applications. You can setup the
Java Plug-In for your appplication manually or you can walk through the Java instrumentation wizard.

If you are using Windows XP SP2, please also make sure that the Windows Update KB884020 is installed, which
resolves problems with the local network communication.

Manual Setup of Ranorex Java Plug-In

1. First of all close all Ranorex Tools.


2. Now you have to determine the path of your active Java runtime Environment to know where to
copy the necessary files to. Open the Java Runtime Environment Settings which can be found in “Java
C ontrol Panel” (Control-Panel -> Java). There you can see the path of your Java Runtime Environment.
If you have more than one Java Runtime Environment installed on your machine, check which one will be
used to execute your Java applications by determining which one is
activated.http://www.microsoft.com/downloads/en/details.aspx?FamilyId=17D997D2-5034-4BBB-B74D-
AD8430A1F7C 8
3. After identifying the path you have to copy each of the following files to its corresponding directory based
on the root folder of your java runtime installation (e.g. “C :\Program Files (x86)\Java\jre6\”). The given
files are located in the Ranorex installation folder (e.g. "C :\Program Files\Ranorex 3.2\Bin")
“accessibility.properties” to \lib
“RanorexAutomation.jar” to \lib\ext
“JavaHelper32/64.dll” to \bin

After restarting you Java application you should be able to use the Ranorex for your Java application under test.

C opyright © 2012 Ranorex

Page 176 of 247


Qt Testing
The Ranorex Automation Framework fully supports test automation of Qt based applications. To ensure that
Ranorex can access UI elements and properties in the Qt application, MSAA (Microsoft Active Accessibility)
support for your Qt application must be enabled. This provides additional information on Qt UI elements to
automation software like Ranorex and can be accomplished by shipping and loading the "Accessible Plug-in"
included in the Qt SDK (Software Development Kit) with the Qt application under test (see below).

Loading Accessible Plug-in for your Qt application:

1. C opy the "accessible" directory (and all its contents) from the Qt SDK (used to build the application
under test) installation folder to the folder of the automated application (e.g. “Program Files/Your-
Application/plugins”). If you do not have access to the Qt SDK which the Qt application is developed
with, please contact the developer of the application and request the "accessible" directory from him.

2. C reate a file called "qt.conf" (or append if the file already exists) in the root directory of the automated
application (e.g. "Program Files/Your-Application") with following content (copy and paste the
following two lines):

[Paths]
Plugins = plugins

Without Accessible Plug-in With Accessible Plug-in

C opyright © 2012 Ranorex

Page 177 of 247


Testing of Legacy Applications
For some older technologies like VB6.0, Delphi or MFC based applications, Ranorex has only limited support in
addressing UI elements in a robust way. With the GDI RawText Plug-In Ranorex increases object recognition for
controls which use the Windows GDI drawing mechanism to display text on screen.

Add Class or Process to GDI Capture List


By default the Ranorex GDI Plug-In is not activated. Use the Ranorex Spy tool to activate the Plug-In for a
specific control.

Add class name to GDI capture list

The pictures below show the different object recognition for a MFC -based menu bar control before and after GDI
activation.

Before ... ... and after GDI activation

You can also add a process name to the GDI capture list by right-clicking on the parent form element of a control
in the Ranorex Spy tree.

Remove Classes or Processes from GDI Capture List


Open the main 'Settings' dialog within Ranorex Spy and click the 'GDI C apture Settings' button to edit the list of
captured class names and processes.

Page 178 of 247


GDI Capture Settings dialog shows
currently observed processes and
class names

Simply delete class or process names which have been added via the context menu from the text boxes shown
above.

C opyright © 2012 Ranorex

Page 179 of 247


General Troubleshooting
This section provides an overview of possible reasons for a limited object recognition with Ranorex tools and
recommends ways to correct a malfuction.

.NET WinForms
.NET Silverlight
Flash/Flex Applications
Win32 Based Applications
Browser (Mozilla Firefox, Google C hrome, Apple Safari)
Image Related Automation or Validation
Geometry Related Issues

.NET WinForms
Ranorex failed to load the assemblies containing the definition of this control. UI element identification capabilities
for this control are limited. There might be several reasons for limited support of .NET WinForms based
applications or controls:

Reason #1:

The automating process (Ranorex executable) and the automated application (AUT) are not started with the same
security rights, i.e. not as the same Windows user.

Solution:

Try starting both applications as the same user.

Reason #2:

Either the automating executable or the AUT are started from a network drive or encrypted folder and
consequently do not have the required security rights.

Solution:

Try copying both applications to a folder on your hard disk.

Reason #3:

The controls that cannot be identified are implemented in a mixed-mode EXE file (not DLL). This can be the case
with some obfuscating applications or assembly merging utilities that create mixed-mode EXE files. The .NET
Framework does not support loading such mixed-mode executables in other processes and that's why Ranorex
cannot recognize controls implemented within them.

Solution:

As a workaround, you can try to automate the non-obfuscated version of your application.

Reason #4:
The controls that cannot be identified are implemented in an assembly that targets a particular
platform/processor and the automating executable targets a different platform/processor. This can cause
problems on 64 bit operating systems, since such assemblies cannot be loaded by the automating process.
Solution:

Try changing the "Target C PU" (Ranorex Studio) or "Platform Target" (Visual Studio) option in the automation
project settings to match the target of the automated application as described in this section. If you don't know
the target C PU/platform of the automated application, first try to change the option to "Any processor" or "Any
C PU", respectively, then try the remaining options.

Reason #5:
The .NET Framework 4.0 Extended package is needed but not installed. An indication for this problem typically is
that controls can correctly be identified by the standalone Ranorex Spy application, but not by the integrated
Page 180 of 247
Ranorex Spy or Recorder in Ranorex Studio.The application under test uses the .NET Framework 4.0 and you
may get Technology Limitation pop-ups saying that specific assemblies cannot be loaded.
Solution:

Either install the .NET Framework 4.0 Extended or if that is not possible always use the standalone Ranorex Spy
and Recorder tools instead of the integrated ones in Ranorex Studio.

Reason #6:
If the application under test is built with the .NET Framework 4.0, a <executableName>.exe.config file (where
<executableName> has to be replaced by the name of the Ranorex executable) needs to reside in the same
folder as the automating Ranorex executable and it needs to contain the configuration below.

Solution:

C reate and add an app.config file with the below content to your project. Make sure that after compiling and when
executing the executable there is a <executableName>.exe.config file in the same folder as the Ranorex
executable with following content:

<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0"/>
<supportedRuntime version="v2.0.50727"/>
</startup>
</configuration>

.NET Silverlight
Ranorex is not able to access UI objects inside your Silverlight application.

Solution:

Please make sure that the Windowless property of your Silverlight application is set to 'False'.

Flash/Flex Applications
After activating the Flash/Flex Plug-In for your applciation using the instrumentation wizard Ranorex is still not
able to recognize Flash/Flex elements within your application.

Reason #1
The AllowScriptAccess parameter in the HTML code that loads a SWF file controls the ability to perform outbound
URL access from within the SWF file.

Solution:
Set this parameter inside the PARAM or EMBED tag to "always".

Reason #2
Your Flash/Flex application was instrumented twice using different versions of Ranorex Flash components.

Solution:

Ensure that only one of the recommended instrumentation approaches for Flash/Flex is used.

Win32 Based Applications


There might be several reasons for limited support of Win32 based applications:

Reason #1:
The automating process is not being run with the required security permissions to access the process under test.
UI element identification capabilities for controls in that process are limited.

Solution:

The automating process (Ranorex executable) and the automated application (AUT) are not started with the same
security rights, i.e. not as the same Windows user. Ensure that both processes are started with the same rights.

Page 181 of 247


Reason #2:
The automating and the automated process do not have the same bit width and Ranorex was unable to start the
32/64 Bit Bridge. UI element identification capabilities for controls in that process are limited.

Solution:

Please contact Ranorex support team for further assistance.

Reason #3:
The automating and the automated process do not have the same bit width and the 32/64 Bit Bridge is disabled.
UI element identification capabilities for controls in that process are limited.

Solution:

Enable the 32/64 Bit Bridge in the General Ranorex Settings.

Browser (Mozilla Firefox, Google Chrome, Apple Safari)


Mozilla Firefox:

UI element identification capabilities for Mozilla Firefox are limited.

Solution:

Please make sure that you have installed and enabled the Ranorex Addon in your Mozilla browser. Please refer to
the Mozilla Firefox instrumentation wizard documentation for more information.

Google Chrome:

UI element identification capabilities for Google C hrome are limited.

Solution:

Please make sure that you have installed and activated the Ranorex Extension in your Goggle browser. Please
refer to the Google C hrome instrumentation wizard documentation for more information.

Apple Safari:

UI element identification capabilities for Apple Safari are limited.

Solution:

Please make sure that you have installed and activated the Ranorex Extension in your Apple browser. Please
refer to the Apple Safari instrumentation wizard documentation for more information.

Image Related Automation or Validation


Ranorex's image based recording ability is limited because the asynchronous dispatching of input events is
disabled.

Solution:

If you experience problems when making image based recordings, please enable asynchronous dispatching of
mouse and keyboard events using the Recorder's settings dialog.

Geometry Related Issues


C ontrols being displaced, staying empty, or being scrolled out of view during automation.

Solution:

Set the "Use Ensure Visible" property of the corresponding repository items (and their parent folders) to "False"
as described in the chapter Repository Items Properties.

C opyright © 2012 Ranorex

Page 182 of 247


RanoreXPath
A RanoreXPath expression is primarily used to uniquely identify UI elements within a desktop or web application. Generally, a RanoreXPath expression consists of:

Adapters
Attributes
and Values

Main components of a RanoreXPath expression

The adapter type specifies the type or classification of a UI element to search for (button, form, text field, listbox, etc.).

Looking at the first part of the RanoreXPath expression '/form[@title='Form 1']' the

'/form' string specifies a search for a UI element of adapter type form.


A Ranorex.Form adapter represents top-level windows such as dialogs or messageboxes on the Windows desktop system.
The attribute value comparison '[@title='Form 1']' specifies the UI element in detail.

As an example the first part of the RanoreXPath expression shown in the pictures will look for a UI element which is of type form and has an attribute called 'title' with the
value 'Form 1'. This form holds a container witch caption 'C ontainer 1', which holds a button with text 'Button 1'.

Hierarchical structure of a RanoreXPath

Use the Ranorex Spy tool to get the RanoreXPath for a particular UI object. To edit a RanoreXPath use the text box in Ranorex Spy or chang the path value of a repository
item directly int the repository view. A more comfortable way to edit RanoreXPath is provided by the Ranorex Path Editor.

Learn more about RanoreXPath:

Used with Ranorex Spy


Used in Ranorex Repository
Used in Test Automation C ode

RanoreXPath Syntax Examples


Advanced RanoreXPath Example
RanoreXPath with Regular Expression

RanoreXPath Syntax Examples


Each RanoreXPath can return multiple GUI elements which match the path query.  RanoreXPath is modeled on W3C XPath.
Axes  
/form/button absolute path identifying all buttons that are children of a form
./button relative path identifying all buttons that are children of the current element
identifies all buttons that are descendants of the root element, i.e. all buttons in all
//button
levels of the element tree
identifies all buttons that are descendants of the  current element, i.e. all buttons in
.//button
the subtree of the current element
../button identifies all buttons that are descendants of the parent of the current element
optional location step fitting a container adapter between form and button; identifies
/form/container?/button
both, '/form/container/button' and '/form/button'
/form/?/button optional location step fitting every adapter between form and button

 
Attributes
/form identifies a top level application
/form[@title='Calculator'] identifies a top level application with the title 'C alculator'
/form[ identifies a top level application with the title 'C alculator' and an attribute of instance
@title='Calculator' and @instance='2'] with value two
/form[
identifies a top level application with the title 'C alculator' or by its process name
@title='Calculator' or @class='SciCalc']
/form/button identifies a button in the application
/form/button[2] identifies the second button in the application
/form/button[-2] identifies the second-to-last button in the application
/form/button[@text='7'] identifies a button with a text attribute value of '7'
/form/button[@text!='7'] identifies a button with a text attribute value that is not '7'

Page 183 of 247


/form/button[@text~'^7'] identifies a button using a regular expression
identifies a button with a location.x value of '100' using the cascaded get function of
/form/button[location.x=100]
the x value of the location attribute
/form/*[@text='7'] identifies any element with a text attribute value of '7'
optional location step fitting a container adapter between form and button; identifies
/form/container?[@caption=’Container 1’]/button
both, '/form/container[@caption=’C ontainer 1’]/button' and '/form/button'
/form/button[?'add'] identifies button with any attribute containing the substring ‘add’ (case-insensitive)
/form/button[@text!=null()] identifies a button where the attribute text is not null
identifies a progress bar with value greater than or equal 13.5 (following
/form/progressbar[@Value>=13.5]
comparison operators are available also: >, <=, <)
identifies a top level application with title attribute value set to value stored in
/form[@title=$var]
variable $var
/form/button[$var] identifies the button with index equals the value stored in the variable $var
identifies an input element on a web document with unique id ‘search’ (supported for
/dom//input[#'search']
web testing)

 
Functions
/form/table/row/cell[first()=‘True‘] identifies the first cell of a row
/form/table/row/cell[last()=‘True‘] identifies the last cell of a row
/form/table/row/cell[index()=2] identifies the second cell of a row
/form[x()>100 and y()>100] identifies a top level application with screen coordinates greater than 100
identifies a button with client coordinates (coordinates of an element relative to its
/form/button[cx()>10 and cy()>10]
parent) greater than 10
/form[width()>100 and height()>100] identifies a top level application with width and height greater than 100.

Advanced RanoreXPath Example


The following example describes how to use RanoreXPath to identify a GUI element not having unique attributes. The example shows how to access a HTML checkbox
using a relative RanoreXPath expression.

Each row in the table represents a user. The users attributes are mapped into separate cells.

1. Identify a user from a list by its name (green highlighted)

<pre>/table/*/tr/td/a[@InnerText='Username']

</pre>
2. Select the corresponding checkbox with a relative path from the name (red highlighted)

<pre>/../../td/input[@type='checkbox']

</pre>
3. Get the full path to the checkbox by combining the two paths.

RanoreXPath with Regular Expression


matches the following button elements: 'sample0', 'sample1', ... 'sample9', 'My
button[@text~'sample[0-9]']
sample26'
listitem[@text~'^sample.*'] matches all elements starting with text value sample
listitem[@text~'.*sample$'] matches all elements ending with text value sample
listitem[@text~'gr(a|e)y'] matches text value gray or grey
listitem[@text~'^sample\ 123$'] matches 'sample 123' (use backslash to escape special characters like space)
matches the regular expression case-insensitive, e.g. 'mytext', 'MYTEXT', 'mYTeXT',
listitem[@text~'(?i:MyTeXt)']
...

The following are special characters that need to be escaped when used in a regular expression by preceding them with a backslash '\'. E.g. when you want to match the text
'Sample.' (with a dot at the end), the dot needs to be escaped: 'Sample\.'. 

C haracter Description
. The dot will match any single character. For example 'Sample.' matches 'Sample1', 'Samplex', etc.
$ The dollar sign will match the end of the string. The expression 'abc$' will match the sub-string 'abc' only if it is at the end of the string.
The alternation character allows either expression on its side to match the target string. The expression 'gr(a|e)y' can match 'gray' or
|
'grey'.
The asterisk indicates that the character to the left of the asterisk in the expression should match zero or more times. For example 'g*gle'
*
matches ggle, gogle, google, gooogle, etc.
The plus is similar to asterisk but there must be at least one match of the character to the left of the + sign in the expression. For
+
example 'go+gle' matches gogle, google, gooogle, etc.
? The question mark (?) matches the character to its left 0 or 1 times. For example, 'colou?r' matches both color and colour.
^ Beginning of the string. The expression '^A' will match an A only at the beginning of the string.
Page 184 of 247
() The parenthesis affects the order of pattern evaluation.

Page 185 of 247


[] Brackets enclosing a set of characters indicate that any of the enclosed characters may match the target character.
The caret immediately following the left-bracket  has a different meaning. It is used to exclude the remaining characters within brackets
[^0-9]
from matching the target string. The expression '[^0-9]' indicates that the target character must not be a digit.
For additional information on regular expressions please consult the corresponding MSDN web site: http://msdn.microsoft.com/en-us/library/az24scfc.aspx

C opyright © 2012 Ranorex

Page 186 of 247


Ranorex UI Adapter
When tracking single UI elements with Ranorex Spy, Ranorex tries to specify the role and technology of the
element. Ranorex recognizes over 30 of the most commonly used types of UI elements. In Ranorex vocabulary
these types are called 'adapters'. Every single element shown within the element tree of Ranorex Spy can be
accessed using the Ranorex UI adapters that the element supports. If Ranorex is not able to assign a more
specific type of adapter to a UI element, it will be displayed as 'Unknown'.

Ranorex adapters provide more convenience when creating automated tests. Here is an example: A Ranorex
Text adapter provides text box related properties like 'Text' or 'SelectionText'. In comparison to a simple Text
adapter, a Ranorex TreeItem adapter provides tree item specific properties and methods like expand or collapse.
Ranorex Spy shows all adapter related properties in the 'Overview' tab.

Properties of a Ranorex 'Text' Properties of a Ranorex 'TreeItem'


Adapter Adapter

The section 'General' in Ranorex Spy shows the general properties which are available for any type of UI
element. All the other information within the 'Overview' tab is related to the type of adapter supported by the
element.

The following example accesses properties of a Ranorex Text adapter:

C#
view plain c opy to c lipboard print

// Create Text adapter from RanoreXPath   
Text textBox = "/form[@title='Calculator']/text[@controlid='403']";   
// Set text value of text box   
textBox.TextValue = "12";   
  
// Check on of the 'General' properties   
if (textBox.Enabled)   
  Report.Info("Text is enabled");  

VB.NET
view plain c opy to c lipboard print

' Create Text adapter from RanoreXPath   
Dim textBox As Text = "/form[@title='Calculator']/text[@controlid='403']"  
' Set text value of text box   
textBox.TextValue = "12"  
  
' Check on of the 'General' properties   
If textBox.Enabled Then  
    Report.Info("Text is enabled")   
End If  
Page 187 of 247
The following example accesses properties of a Ranorex TreeItem adapter:

C#
view plain c opy to c lipboard print

// Create TreeItem adapter from RanoreXPath   
TreeItem treeItem= "/form[@title='Documents and Settings']/*/*/*/*  
                         /*/*/treeitem[@text='Documents and Settings']";   
// Collapse and expand tree item   
if (treeItem.Expanded)   
  treeItem.Collapse();   
else  
  treeItem.Expand();  

VB.NET
view plain c opy to c lipboard print

' Create TreeItem adapter from RanoreXPath   
Dim treeItem As TreeItem = "/form[@title='Documents and    
     Settings']//treeitem[@text='Documents and Settings']"   
' Collapse and expand tree item   
If treeItem.Expanded Then  
    treeItem.Collapse()   
Else  
    treeItem.Expand()   
End If  

Multiple Adapters for one GUI element


In addition to the Ranorex standard adapters which represent the logical view of a UI element, Ranorex provides
technology-specific adapters with more information.

As an example the Ranorex WinForms Plug-In is able to provide more information about a simple button in a .NET
application. This additional information is provided via an additional adapter called 'C ontrol'. The following
screenshots compare the information shown by Ranorex Spy for a Win32 and a WinForms button:

Button of calculator application Button of a .NET WinForms


which provides a Ranorex Button application which provides an
Page 188 of 247
and a Ranorex NativeWindow additional Ranorex Control adapter
Adapter

The C ontrol adapter, which is available for .NET WinForms applications, allows Ranorex to access more properties
in the application under test, like the background color or font size of the displayed text. Simply convert a
standard Button adapter to a WinForms C ontrol adapter as follows:

C#
view plain c opy to c lipboard print

// Create Button adapter with RanoreXPath   
Ranorex.Button button= "/form[@controlname='TestedApp']   
                  /button[@controlname='button1']";   
// Convert Button adapter to Control adapter   
Ranorex.Control winFormsButton = new Ranorex.Control(button);   
// Call 'GetPropertyValue' method provided by the Control adapter   
Color color = winFormsButton.GetPropertyValue<Color>("BackColor");  

VB.NET
view plain c opy to c lipboard print

' Create Button adapter with RanoreXPath   
Dim button As Ranorex.Button = "/form[@controlname='TestedApp']   
    /button[@controlname='button1']"   
' Convert Button adapter to Control adapter   
Dim winFormsButton As New Ranorex.Control(button)   
' Call 'GetPropertyValue' method provided by the Control adapter   
Dim color As Color = winFormsButton.GetPropertyValue(Of Color)("BackColor")  

It is not required to work with Ranorex adapters. It's also possible to write automation code using Ranorex
Element instances (which are used internally by Ranorex adapters) - it's just more difficult.

Note: UI objects managed within Ranorex repositories always use Ranorex adapters.

C opyright © 2012 Ranorex

Page 189 of 247


Android Testing
Learn how to automate your Android app testing for different devices and languages. The following sections will
explain how to set up an environment for Android testing, how to generate and execute a test and what to do if
any problems occur. The Android app KeePassDroid is taken as an example how to automate mobile applications
using Ranorex.

Infrastructure
Getting Started
Record your Android test
Run your test on any Android device

Infrastructure
Before getting started with Android test automation, it’s necessary to make sure that the system under test (the
mobile devices) and the machine running the tests (where Ranorex is installed) are in the same network.

Automated Android app testing over Wi-Fi

As the recording and executing of tests is processed via the network, there is no need for an USB connection
between the system under test and the machine running the test.

But it is recommended to have your system under test plugged into a power supply during test recording and
execution.

Getting Started
This quick start guide will show you how easy it is to record your Android test and execute the test on different
devices and Android languages.

Start your first recording by pressing the record button in Ranorex Recorder.

Next to starting a “Global Recording”, “Run an Application” or “Open a Browser” it is also possible to start a
“Mobile Recording”.

Page 190 of 247


Record Settings dialog

Add Device
Open the “Manage Device” dialog by pressing the Devices button from the Record Settings dialog.

If no devices have been added yet, the Install Services description will be shown.

Install Services description

Note: the QR code and description can be shown at any time by pressing the “Install Service” button.

By using the QR code with a bar code reader app or by entering the URL mentioned in the description, the
Ranorex Service app can be downloaded and installed on the mobile device.

Installation of the Ranorex Service app using the QR


code

After downloading and installing, the Ranorex Service app will be started on the device which can now be added
to the list of devices in the Manage Devices dialog by pressing the “Add” button.

Page 191 of 247


Add Android device

If you would like to add an emulator or have problems with a device, have a look at the Manage Devices and the
Troubleshooting section.

Added Android device

Instrument and Deploy your Android App


After setting up the Android device, the app which should be automated has to be instrumented and deployed to
the device.  The Instrumentation wizard for instrumenting and deploying an APK file can be started from “Manage
Devices” dialog, “Record Settings” dialog, or directly by starting the instrumentation wizard as described in the
chapter Instrumentation Wizard.

As mentioned before, the Android app KeePassDroid is taken as an example how to automate mobile applications
using Ranorex. The APK file can be downloaded at http://keepassdroid.googlecode.com/files/KeePassDroid-
1.9.9.apk.

After choosing a device to deploy and an APK file to instrument, the process will be started by pressing the “Next”
button.

Page 192 of 247


Android Instrumentation Wizard

After the instrumentation of the APK file, it will be automatically deployed to the selected device.

Successfully finished instrumenting and deploying


APK

To finish the instrumentation and deployment process, the installation has to be confirmed on the mobile device.

Confirm installation of
instrumented APK

Record your Android test


After preparing the device and instrumenting the APK, the recording can be started by choosing the device on
which the test should be executed and the app which should be tested.

Page 193 of 247


Mobile Recording with chosen device and app

By pressing the “Start” button, the instrumented app will be automatically started on the mobile device and a
notification on the desktop will inform the user, that actions will be recorded directly on the mobile device.

Record notification

During the recording process, the action table of the Ranorex Recorder will give a good overview over the
performed steps, as the table is updated live.

Action table updates during recording process

Note: The recommended way to add a value to a text box is to tap on the text box before typing.

Note: It’s recommended to wait a short period of time before operating on list elements after scrolling the list.

Note: It’s recommended to touch the text of a list element and not the empty space next to the text when
operating a list element.

During recording it’s possible to add validations using the “Validation” button. By pressing the button, a dialog will
open where the element which should be validated can be chosen.

Page 194 of 247


Select element to validate

After choosing an element, the “Validate Element” dialog will pop up. In this dialog, the attributes which should be
validated can be selected.

Choose attribute to validate

Additionally to recording actions, it’s also possible to add actions to the action table after the recording process.
This can be done by dragging a repository item to the action table and choosing the action which should be
performed from the menu.

Adding actions manually

After recording and adding actions manually, the action table might look something like the following.

Page 195 of 247


Action table

Action #1 is a “Run Mobile App” action which starts the instrumented APK file on the selected device.

Action # 2 is a Touch Event on a button. There are 5 different kinds of touch events recognized by Ranorex:

a normal “Touch” which is equivalent to a mouse click on a desktop machine,


a “Long Touch” which typically opens a context menu
and “Touch Start”, “Touch Move” and “Touch End” for simulating a drag gesture.

Action # 4 is a “Set Value” action, which is typically used for keyboard input.

Action # 6 is a “Wait For Not Exists” action, which is useful when having for example an item indicating a loading
process and the automation should go ahead when the item has disappeared.

Action # 7 is a “Validate” action as described before.

Action # 8 is a “Get Value” action, which can be used to write back an attribute value of a control to a variable for
further processing.

Action # 9 is a “Report” action, which is used to add information to the test report.

Action # 10 is a “Invoke Action” which performs a scroll action on a list control to its index “0”. “Invoke Actions”
directly call the corresponding method of the selected control.

Action # 11 is a “Mobile Key Press” action. “Mobile Key Press” actions simulate the physical buttons “Back” and
“Menu” of the mobile device.

Action # 12 is a “C lose Application” action. “C lose Application” actions stop the selected application on the mobile
device.

Note: Make sure to add a “C lose Application” action, when running your test on different devices, because if the
app will not be closed on the devices, the app on the first identified device will be automated.

Stop Recording
After performing the test on the mobile device, the recording process can to be stopped by pressing the “Stop”
button.

Stop recording

Run Test
After recording and altering the action table, the test can be executed on the mobile device by pressing the “Run”
button.

Run your test on any Android device


We will show you how easy it is to run your Android test on any device. Therefore add another device and
instrument and deploy the application under test, as described earlier in this chapter.

Page 196 of 247


Note: Make sure to add a “C lose Application” action, when running your test on different devices, because if the
app will not be closed on the devices, the app on the first identified device will be automated.

Add a "Close Application" action to ensure that the


recording will be executed on the right device

After doing so, make the “Device Display Name” of the “Run Mobile App” action in your recording variable.

Make the Device, the test will be executed, variable

After making the device variable, open the “Data Source” dialog of the test case holding your recording and add
a new simple data table holding the names of the devices you want to run the test on.

Page 197 of 247


After doing so, switch to the “Data Binding” tab and bind the data source to the variable in your recording.

Have a look at Lesson 3: Data-Driven Testing if you want to learn more about the data-driven approach of
testing.

Now, the test suite is prepared for running the recording on different devices. After successfully running the test,
the test report should look something like the following.

Successfully executed test on two devices

Page 198 of 247


C opyright © 2012 Ranorex

Page 199 of 247


Manage Devices
Within the "Manage Devices" dialog, new Android devices can be added to make them automatable by Ranorex.

Add a device
Add a device manually
Show device information

Add a device
The “Manage Device” dialog can be opened from the Devices pane or from the Record Settings dialog.

If no devices have been added yet, the Install Services description will be shown.

Install Services description

Note: the QR code and description can be shown at any time by pressing the “Install Service” button.

By using the QR code with a bar code reader app or by entering the URL mentioned in the description, the
Ranorex Service app can be downloaded and installed on the mobile device.

Installation of the Ranorex Service app

Page 200 of 247


using the QR
code

After downloading and installing, the Ranorex Service app will be started on the device, which can now be added
to the list of devices in the Manage Devices dialog by pressing the add button.

Add device

Add a device manually


If a device cannot be found automatically, it can be added by entering name and IP address manually.

Note: To add an emulator, please type in "127.0.0.1" in the IP address field. (Please make sure that only one
emulator is running at the same time)

The IP address can be found within the service app on the device by pressing the “Details” button.

Page 201 of 247


Ranorex Service app

Details view

Add mobile device

After adding a device, it is available within the “Manage Devices” dialog.

Page 202 of 247


New added device

Devices can be disabled by pressing the “Disable” button.  By disabling devices, they will not be available in
devices pane and “Record Settings” dialog until they are enabled again.

The name, IP address and port of a device can be changed by pressing the Edit button.

By pressing the “Remove” button, the selected device will be removed for the list of devices.

Pressing the Reconnect/Retry button will try to connect to the device over the network. 

Show device information


If a device is no longer reachable, it will be marked with a red “x-sign”.

By moving your mouse over the device, a tooltip will appear, giving detailed information about the problem.

Failed to connect to mobile device

C opyright © 2012 Ranorex

Page 203 of 247


Troubleshooting
If you have connection problems try to consider following potential sources of error:

Make sure that the system under test (the mobile devices) and the machine running the tests (where
Ranorex is installed) are in the same network.
After changing Wi-Fi settings on the device, make sure to restart the device.
Try to increase the Discovery Timeout at the “Mobile” section in the “Plugins” tab of general settings.
Try to find out more about the connection problem by moving your mouse over the device in “Manage
Devices” dialog.

If you have more than one device from the same model, make sure to set unique device names for these
devices in the service app on the devices.

C opyright © 2012 Ranorex

Page 204 of 247


Web Testing
The Ranorex Web Plugins (for Microsoft Internet Explorer, Mozilla Firefox, Google C hrome and Apple Safari) allow
you to test the UI of web applications in the same way you would automate standard desktop applications.

Architecture of Websites in the Ranorex Framework


Handling of AJAX
Find or filter Web Elements
List elements of a table and set css style
C ross-Browser Testing
Set inputs, tag attributes and perform a click without mouse
Recordings & Repositories
Execute javascript code
Handling of layer menus

Architecture of Websites in the Ranorex Framework


Ranorex is able to access the complete HTML architecture of a web document. Use the Ranorex Spy to analyze
the structure and the content of a web application and to see which information is accessible during automation.

All open websites are shown as a single Dom node in the spy tree. In addition to standard browser hosted
applications, Ranorex is able to see embedded browser objects too (e.g. compiled help files). Additional each
tab item within a browser window is presented as a separate Dom node within the spy tree.

The web document and its HTML structure can be identified using RanoreXPath. Similar to XPath in HTML,
the RanoreXPath provides a simple search mechanism for finding single or multiple web elements within a web
page.

WebDocument Adapter
The WebDocument Adapter creates a representation of the complete web-site including all tags (e.g. the header
tag, body tag, etc.). Furthermore it offers useful ways to make your test scripts more effective.

The following sample shows how to use these features:

C#
view plain c opy to c lipboard print

// Identify a web document by its title   
WebDocument webDocument = "/dom[@caption='Ranorex Test Page']";   
// Open a website   
webDocument.Navigate("http://www.ranorex.com");   
// Wait until the document is loaded   
webDocument.WaitForDocumentLoaded();   
// Execute a javascript code   
webDocument.ExecuteScript("history.back();");  

Page 205 of 247


VB.NET
view plain c opy to c lipboard print

' Identify a web document by its title   
Dim webDocument As WebDocument = "/dom[@caption='Ranorex Test Page']"  
' Open a website   
webDocument.Navigate("http://www.ranorex.com")   
' Wait until the document is loaded   
webDocument.WaitForDocumentLoaded()   
' Execute a javascript code   
webDocument.ExecuteScript("history.back();")  

Find or filter Web Elements


The Ranorex Framework offers a wide range of adapters for each HTML tag elements (e.g.: ATag adapter for
<a> tags). Each adapter has specific methods and attributes; the link tag (<a>) for example has additional
attributes like HREF, TARGET and REL.

C#
view plain c opy to c lipboard print

// Start IE with a specific website   
System.Diagnostics.Process.Start("iexplore.exe",  "www.ranorex.com/web-testing-examples");
  
// Identify the webdocument by its title   
WebDocument webDocument = "/dom[@caption='Ranorex Test Page']";   
// Find a link by its link text (innertext)   
ATag link = webDocument.FindSingle(".//a[@innertext='simple link']");   
link.Click();  

VB.NET
view plain c opy to c lipboard print

' Start IE with a specific website   
System.Diagnostics.Process.Start("iexplore.exe", "www.ranorex.com/web-testing-examples")   
' Identify the webdocument by its title   
Dim webDocument As WebDocument = "/dom[@caption='Ranorex Test Page']"  
' Find a link by its link text (innertext)   
Dim link As ATag = webDocument.FindSingle(".//a[@innertext='simple link']")   
link.Click()  

Cross-Browser Testing
During the installation of Ranorex the setup package automatically installs add-ins for all supported browsers,
which enable the communication between the Ranorex Browser Plug-In and the specific browser. If you have
problems with instrumenting a specific browser use the Ranorex Instrumentation wizard as explained here.

C reating tests for Firefox does not differ to creating tests for Internet Explorer or any other supported browser.
All web UI elements are specified through RanoreXPath, which uses HTML attributes and values for identification.
For this reason a single web repository can be used for testing all supported types of web browsers. Learn more
about how to test multiple browsers with a test case based on one single repository introduced by our web testing
example project, which is part of the Ranorex setup package.

Automation of browser specific elements (e.g. Pop-Up window)


Handling of browser specific UI controls requires a separate RanoreXPath for each browser specific element. That
means if you would like to click on a Pop-Up dialog in different browser, you will have to add a separate
repository item for each dialog.

The Ranorex Automation library provides you with a property called "BrowserName" which tells you the current
browser of the web site under test:

C#
Page 206 of 247
view plain c opy to c lipboard print

// Click the OK button in popping up dialog of one of the supported browser   
// If the current browser is Internet Explorer   
if(webDocument.BrowserName == "IE")   
{   
    Button okIE = "/form[@processname~'(iexplore|IEXPLORE)']//button[@text='OK']";   
    okIE.Click();   
}   
// If the current browser is Mozilla Firefox   
else if(webDocument.BrowserName == "Mozilla")   
{   
    Button okFF = "/form[@processname='firefox']//button[@text='OK']";   
    okFF.Click();   
}   
// If the current browser is Google Chrome   
else if(webDocument.BrowserName == "Chrome")   
{   
    Button okChrome = "/form[@processname='chrome']//button[@text='OK']";   
    okChrome.Click();   
}   
// If the current browser is Apple Safari   
else if(webDocument.BrowserName == "Safari")   
{   
    Button okSafari = "/form[@processname='Safari']//button[@text='OK']";   
    okSafari.Click();   
}  

VB.NET
view plain c opy to c lipboard print

' Click the OK button in popping up dialog of one of the supported browser   
' If the current browser is Internet Explorer   
If webDocument.BrowserName = "IE" Then  
    Dim okIE As Button = "/form[@processname~'(iexplore|IEXPLORE)']//button[@text='OK']"  
    okIE.Click()   
' If the current browser is Mozilla Firefox   
ElseIf webDocument.BrowserName = "Mozilla" Then  
    Dim okFF As Button = "/form[@processname='firefox']//button[@text='OK']"  
    okFF.Click()   
End If  
' If the current browser is Google Chrome   
ElseIf webDocument.BrowserName = "Chrome" Then  
    Dim okChrome As Button = "/form[@processname='chrome']//button[@text='OK']"  
    okChrome.Click()   
End If  
' If the current browser is Apple Safari   
ElseIf webDocument.BrowserName = "Safari" Then  
    Dim okSafari As Button = "/form[@processname='Safari']//button[@text='OK']"  
    okSafari.Click()   
End If  

Recordings & Repositories


Ranorex Recorder provides the same capture and replay functionality, which is used for standard client desktop
applications. The recorder automatically creates action items for each recorded user action within the Recorder's
actions table. The corresponding repository contains all required UI web element objects for used within the
actions table.

Page 207 of 247


Repositories and the WebDocument
The following example shows hot to acces the methods of the WebDocument using a repository:

C#
view plain c opy to c lipboard print

// Load repository   
ProjectRepository repo = ProjectRepository.Instance;   
// Open a website   
repo.WebPage.Self.Navigate("http://www.ranorex.com");   
// Wait until the document is loaded     
repo.WebPage.Self.WaitForDocumentLoaded();  

VB.NET
view plain c opy to c lipboard print

' Load repository   
Dim repo As ProjectRepository = ProjectRepository.Instance   
' Open a website   
repo.WebPage.Self.Navigate("http://www.ranorex.com")   
' Wait until the document is loaded     
repo.WebPage.Self.WaitForDocumentLoaded()  

C opyright © 2012 Ranorex

Page 208 of 247


Samples
The following web testing examples show how to access typical web elements of a web page.

Handling of AJAX
List elements of a table and set css style
Set inputs, tag attributes and perform a click without mouse
Execute javascript code
Handling of layer menus

The Ranorex web site provides a small page especially for web testing purposes:

www.ranorex.com/web-testing-examples/

All examples are available in the Web Test Sample Ranorex Studio and Visual Studio project located within
your installation folder (..\Samples\WebTestSample)

Handling of AJAX

C#
view plain c opy to c lipboard print

GlobalRepository repo = GlobalRepository.Instance;   
WebDocument webDocument = repo.WebPage.Self;   
// Fill out the AJAX form   
InputTag input1 = webDocument.FindSingle(".//form[@id='ajax-form']/fieldset//input
[@name='value1']");   
input1.EnsureVisible();   
input1.Value = "Size";   
InputTag input2 = webDocument.FindSingle(".//form[@id='ajax-form']/fieldset//input
[@name='value2']");   
input2.Value = "Weight";   
InputTag checkbox = webDocument.FindSingle(".//form[@id='ajax-form']/fieldset//input
[@name='checkbox2']");   
checkbox.Checked = "true";   
SelectTag selectColor = webDocument.FindSingle(".//form[@id='ajax-form']/fieldset//select
[@name='color2']");   
selectColor.TagValue = "blue";   
// Submit data   
InputTag submit = webDocument.FindSingle(".//form[@id='ajax-form']//input[@id='submit-
ajax']");   
submit.Click();   
Page 209 of 247
  
// Wait for the ajax request for max 10 seconds (10000 milliseconds)   
PreTag result = webDocument.FindSingle(".//div[@id='ajax_response']/div/pre", 10000);  

VB.NET
view plain c opy to c lipboard print

Dim repo As GlobalRepository = GlobalRepository.Instance   
Dim webDocument As WebDocument = repo.WebPage.Self   
' Fill out the AJAX form   
Dim input1 As InputTag = webDocument.FindSingle(".//form[@id='ajax-form']/fieldset//input
[@name='value1']")   
input1.EnsureVisible()   
input1.Value = "Size"  
Dim input2 As InputTag = webDocument.FindSingle(".//form[@id='ajax-form']/fieldset//input
[@name='value2']")   
input2.Value = "Weight"  
Dim checkbox As InputTag = webDocument.FindSingle(".//form[@id='ajax-form']/fieldset//input
[@name='checkbox2']")   
checkbox.Checked = "true"  
Dim selectColor As SelectTag = webDocument.FindSingle(".//form[@id='ajax-
form']/fieldset//select[@name='color2']")   
selectColor.TagValue = "blue"  
' Submit data   
Dim submit As InputTag = webDocument.FindSingle(".//form[@id='ajax-form']//input
[@id='submit-ajax']")   
submit.Click()   
  
' Wait for the ajax request for max 10 seconds (10000 milliseconds)   
Dim result As PreTag = webDocument.FindSingle(".//div
[@id='ajax_response']/div/pre", 10000)  

List elements of a table and set css style

C#
view plain c opy to c lipboard print

GlobalRepository repo = GlobalRepository.Instance;   
WebDocument webDocument = repo.WebPage.Self;   
  
// List all elements of a table   
foreach (TrTag row in repo.WebPage.DivTagContent.TableTagSimpletable.Find("./tbody/tr"))   
{   
    string rowInfo = "";   
  
    TdTag rowNameCell = row.FindSingle("./td[2]");   
    rowInfo += "Row index: " + rowNameCell.PreviousSibling.InnerText + ", ";   
    rowInfo += "Row name: " + rowNameCell.InnerText + ", ";   
    rowInfo += "Row value: " + rowNameCell.NextSibling.InnerText + ", ";   
  
    // Get all cells from the row   
    rowInfo += "All Cells: ";   
    foreach (TdTag cell in row.Find("./td"))   
    {   
        rowInfo += cell.InnerText + ", ";   
        // Move the mouse to each cell element   
        cell.MoveTo();   
        // Set css style   
        cell.SetStyle("background-color","#33ff00");   
    }   
  
    Report.Info(rowInfo);   
}  

VB.NET
Page 210 of 247
view plain c opy to c lipboard print

Dim repo As GlobalRepository = GlobalRepository.Instance   
Dim webDocument As WebDocument = repo.WebPage.Self   
  
' List all elements of a table   
For Each row As TrTag In repo.WebPage.DivTagContent.TableTagSimpletable.Find("./tbody/tr")
  
    Dim rowInfo As String = ""  
  
    Dim rowNameCell As TdTag = row.FindSingle("./td[2]")   
    rowInfo += "Row index: " & rowNameCell.PreviousSibling.InnerText & ", "  
    rowInfo += "Row name: " & rowNameCell.InnerText & ", "  
    rowInfo += "Row value: " & rowNameCell.NextSibling.InnerText & ", "  
  
    ' Get all cells from the row   
    rowInfo += "All Cells: "  
    For Each cell As TdTag In row.Find("./td")   
        rowInfo += cell.InnerText & ", "  
        ' Move the mouse to each cell element   
        cell.MoveTo()   
        ' Set css style   
        cell.SetStyle("background-color", "#33ff00")   
    Next  
  
    Report.Info(rowInfo)   
Next  

Set inputs, tag attributes and perform a click without mouse

C#
view plain c opy to c lipboard print

// Use mouse and keyboard to set Name   
repo.WebPage.TestForm.InputTagTestname.Click();   
Keyboard.Press("Test Name");   
// Set email address directly via 'Value'   
repo.WebPage.TestForm.InputTagTestemail.Value = "test@ranorex.com";   
// Open calendar form   
repo.WebPage.TestForm.ButtonTagCalendar.Click();   
// Select the 22th of the current month   
repo.WebPage.TdTag_22nd.Click();   
  
// Select each item of list box   
foreach (OptionTag option in repo.WebPage.TestForm.SelectTagTestmultiple.Find(".//option"))
  
{   
    option["selected"] = "selected";   
}   
  
// Perform a click without moving the mouse to the button   
repo.WebPage.TestForm.InputTagSubmit.PerformClick();  

VB.NET
view plain c opy to c lipboard print

' Use mouse and keyboard to set Name   
repo.WebPage.TestForm.InputTagTestname.Click()   
Keyboard.Press("Test Name")   
' Set email address directly via 'Value'   
repo.WebPage.TestForm.InputTagTestemail.Value = "test@ranorex.com"  
' Open calendar form   
repo.WebPage.TestForm.ButtonTagCalendar.Click()   
' Select the 22th of the current month   
repo.WebPage.TdTag_22nd.Click()   
  
' Select each item of list box   
For Each [option] As OptionTag In repo.WebPage.TestForm.SelectTagTestmultiple.Find
Page 211 of 247
(".//option")   
    [option]("selected") = "selected"  
Next  
  
' Perform a click without moving the mouse to the button   
repo.WebPage.TestForm.InputTagSubmit.PerformClick()  

Execute javascript code

C#
view plain c opy to c lipboard print

webDocument.ExecuteScript("history.back();");  

VB.NET
view plain c opy to c lipboard print

webDocument.ExecuteScript("history.back();")  

Handling of layer menus

C#
view plain c opy to c lipboard print

WebDocument webDocument = "/dom[@caption='Ranorex Test Page']";   
  
DivTag topMenuDiv = webDocument.FindSingle(".//div[@id='top-menu']");   
// Bring the main menu to the front   
topMenuDiv.EnsureVisible();   
// Automating a dropdown menu   
foreach (LiTag item in topMenuDiv.Find(".//li[@visible='true']"))   
{   
    Mouse.MoveTo(item);   
    // Move the mouse to each submenu item   
    foreach (LiTag subitem in item.Find(".//li[@visible='true']"))   
        Mouse.MoveTo(subitem);   
}  

VB.NET
view plain c opy to c lipboard print

Dim webDocument As WebDocument = "/dom[@caption='Ranorex Test Page']"  
  
Dim topMenuDiv As DivTag = webDocument.FindSingle(".//div[@id='top-menu']")   
' Bring the main menu to the front   
topMenuDiv.EnsureVisible()   
' Automating a dropdown menu   
For Each item As LiTag In topMenuDiv.Find(".//li[@visible='true']")   
    Mouse.MoveTo(item)   
    ' Move the mouse to each submenu item   
    For Each subitem As LiTag In item.Find(".//li[@visible='true']")   
        Mouse.MoveTo(subitem)   
    Next  
Next  

C opyright © 2012 Ranorex

Page 212 of 247


Ranorex Studio IDE
Ranorex Studio is an Integrated Development Environment for .Net framework applications written in C # and
VB.Net.

Ranorex Studio is based on SharpDevelop, an open source tool.


The following paragraphs will explain individual functionality provided by Ranorex Studio:

C reate
Build
Run
Adding New Items
Solution Explorer
Debugging
C ode C ompletion
C ode C onversion
C ode Navigation
C ode Generation
Refactoring

C opyright © 2012 Ranorex

Page 213 of 247


Create
The chapter Recording a Test already explains how to create a new Ranorex Solution. Within a Ranorex Solution different kinds of projects can be created.

“New Project” dialog

A project holding a Ranorex Test Suite which may contain recordings and code modules. This might be your first choice when starting with
Ranorex Test Suite
Ranorex Studio
Ranorex Test Suite Module
A project holding recordings and code modules which can be shared and reused
Library
Ranorex C lass Library A project for creating classes which are used in other applications
Ranorex C onsole Application A project that creates a command line application
Ranorex Windows Application A project that creates an application with a windows interface
After choosing a project type and a name for the project, a project will be created in the solution and Ranorex Studio is ready for you to start developing.

Ranorex Studio

C opyright © 2012 Ranorex

Page 214 of 247


Build
After creating your application, it can be built using the “Build” menu.

“Build” Menu

Within this menu, either the whole solution, or a specific project in the solution can be built, rebuilt or cleaned.

Build messages will be shown in the “Output” window.

“Output” window

Build Errors and Warnings will be displayed in the “Errors” window.

“Errors” window

Project specific settings can be defined in the ”Project Options” dialog, which can be accessed from the “Project”
menu.

Opening “Project Options” menu


Page 215 of 247
item

To name some of these settings, you can set the name or the type of the generated assembly in the “Application”
tab, for example.

“Project Options” “Application” tab

You can also set the target C PU and framework or the output path in the “C ompiling” tab.

“Project Options” “Compiling” tab

C opyright © 2012 Ranorex

Page 216 of 247


Run
After building the project successfully, it can be executed from the “Debug” menu either with or without
debugger.

“Debug” menu

C opyright © 2012 Ranorex

Page 217 of 247


Adding New Items
Ranorex Studio provides several different templates which can be added to a project either via the “Project”
menu, or within the “Project Explorer” context menu.

Add new item through “Project” menu

Adding new item through “Project Explorer” context


menu

Page 218 of 247


“New File” dialog

Additional to Ranorex specific files as

C ode Module,
Recording Module and
Repository

programming language specific files like

C lass,
Interface,
Struct and
Form

can also be added just the same as

empty resource and


text files.

After adding a Form it’s possible to use a forms designer which allows to visually design the UI as described
explicitly in the article “Visually Designing Forms” posted at SharpDevelop C ommunity Blog.

C opyright © 2012 Ranorex

Page 219 of 247


Solution Explorer
Besides adding new items to the project, the “Solution Explorer” allows to perform some other assistant options
to edit your solution.

For example adding folders to organize projects by separating recording modules from user code modules.

Add new folder to a project in solution browser

Additionally you are able to delete unused files. This feature is useful especially to delete outdated log files. 
Alternatively, unused files can be excluded from the project without deleting them from the solution.

Page 220 of 247


Delete file from project

It’s also possible to redefine the “Start Up Project” of a solution.

Page 221 of 247


Set project as StartUp project

C opyright © 2012 Ranorex

Page 222 of 247


Debugging
Ranorex provides the possibility to debug code directly in the development environment. To make the Debugger stop at a specific position in your code, you can set
breakpoints.
Breakpoints can either be set

by clicking on the left margin at the line you want to set it, or

by putting the cursor to the line you want to add a breakpoint, open the “Debug” menu an choose “Toggle Breakpoint”.

By setting a breakpoint, a red circle will be added at the margin and the line of code will be highlighted red. The breakpoint can be removed in the same way as it has been
added.

After setting a breakpoint the debugger can be started by executing your application as described in the chapter Run.

Note:  To run an application with debugger, it’s necessary to not choose “Run without Debugger” from menu.

The application will start and Ranorex Studio will switch to the “Debug Layout” which causes the following menu items to be available from “Debugger” menu and toolbar:

C ontinue Debugging C ontinues execution

Stop Process Forces the process to stop

Step Over Executes the statement on the current line but it will not step into

Step Into Executes the statement on the current line and stops at the first line of code inside the method

Step Out Finishes executing the current method and returns to its parent method

Debugging menu Items

Debugging toolbar items

To skip several lines of code and continue debugging on a specific line, the context menu item “Set C urrent Statement” can be chosen by right-clicking on the line and
choosing “Set C urrent Statement” from the context menu.

Page 223 of 247


Context menu “Set Current
Statement”

In paused mode, the actual state of the individual objects can be diagnosed.

The following windows can be activated in the sub-menu “Debug” which is part of the “View” menu.

Debug sub menu

C allstack Shows method calls currently on stack.


Local Shows variables defined in the function currently being executed, arguments passed into the current function and fields and properties of the class where the
Variables function is defined.
Shows all expressions added to the watch list. Expressions can be added by right-clicking on the window, choosing “Add” from context menu and entering the
Watch
expression. Expressions can also be added by selecting them in code and dragging them into the “Watch” window.
Additionally to the different views it’s also possible to diagnose individual objects directly in code using the tool tips popping up when moving the mouse over them.

Note: If Visual Studio 2010 is installed on the machine running Ranorex Studio, debugging might be slow. To overcome this issue it is recommended to search the key
“LowLevelHooksTimeout” in the registry and delete all occurrences.

C opyright © 2012 Ranorex

Page 224 of 247


Code Completion
Ranorex supports code completion as you type.

Code Completion in Ranorex

Further details about how this works can be found in the article C ode C ompletion posted at SharpDevelop
C ommunity Blog.

C opyright © 2012 Ranorex

Page 225 of 247


Code Conversion
With Ranorex Studio it is possible to convert a single code file as well as whole projects from C # to VB.NET and
vice versa.

This can be performed by right-clicking on the specific element in the Project Explorer and choosing “C onvert”
from the context menu.

Convert the whole project from C# to VB.NET

C opyright © 2012 Ranorex

Page 226 of 247


Code Navigation
With Ranorex Studio several features for an intuitive and quick navigation in code are supported. Further details
can be found in the article C ode Navigation posted at SharpDevelop C ommunity Blog.

C opyright © 2012 Ranorex

Page 227 of 247


Code Generation
Ranorex Studio can help you saving time with providing you auto generated code and code templates as
described in the article C ode Generation posted at SharpDevelop C ommunity Blog.

C opyright © 2012 Ranorex

Page 228 of 247


Refactoring
Ranorex Studio supports several mechanisms to refactor code. Further details can be found in the
article Refactoring posted at SharpDevelop Community Blog.

C opyright © 2012 Ranorex

Page 229 of 247


Visual Studio Integration
This example illustrates how to use Ranorex within a simple Visual Studio C # console application. It shows how to
create a new Visual Studio C # console application and how to start and automate the Windows C alculator.

Note: The sample works with both Microsoft Visual Studio 2005 and 2008.

Create a new Visual Studio project


Start Microsoft Visual Studio. From the 'File' menu click 'New Project' to open the New Project Dialog. In this
example we use C # as programming language. C hoose another language if you'd like to implement Ranorex
code in VB.NET or Visual C ++.

Create a new Console Application with Microsoft


Visual Studio

Add Ranorex core assemblies as references


Right-click the 'References' folder within the projects 'Solution Explorer' and open the 'Add Reference' dialog.
Select the components “System.Drawing”, “Ranorex C ore” and all "Ranorex Plugin"-References.

Add new references ... ... select System.Drawing


and Ranorex.Core

Write some Ranorex automation code


Open the file 'Program.cs' and add following 'using' statement to your existing using section:

C#
view plain c opy to c lipboard print

Page 230 of 247


using System.Drawing;   
using Ranorex;  

VB.NET
view plain c opy to c lipboard print

Imports System.Drawing   
Imports Ranorex  

Mark the main thread with the attribute [STAThread] and change the return value of the Main function to int.

C#
view plain c opy to c lipboard print

[STAThread]   
static int Main(string[] args)  

VB.NET
view plain c opy to c lipboard print

<STAThread> _   
Public Shared Function Main(args As String()) As Integer  

Add the following code lines to the 'Main' routine of the class 'Program':

C#
view plain c opy to c lipboard print

int error = 0;   
  
try  
{   
    System.Diagnostics.Process.Start("calc.exe");   
    Form form = Host.Local.FindChild<Ranorex.Form>("Calculator");   
    form.Activate();   
  
    Button button = form.FindSingle<Ranorex.Button>(".//button[@controlid='132']");   
    button.Click();   
  
    button = form.FindSingle<Ranorex.Button>(".//button[@controlid='92']");   
    button.Click();   
  
    button = form.FindSingle<Ranorex.Button>(".//button[@controlid='133']");   
    button.Click();   
  
    button = form.FindSingle<Ranorex.Button>(".//button[@controlid='121']");   
    button.Click();   
}   
}   
catch (RanorexException e)   
{   
    Console.WriteLine(e.ToString());   
    error = -1;   
}   
  
return error;  

VB.NET
view plain c opy to c lipboard print

Dim returnError As Integer = 0   
  
Page 231 of 247
Try  
  System.Diagnostics.Process.Start("calc.exe")   
  Dim form As Form = Host.Local.FindChild(Of Ranorex.Form)("Calculator")   
  form.Activate()   
  
  Dim button As Button = form.FindSingle(Of Ranorex.Button)(".//button[@controlid='132']")
  
  button.Click()   
  
  button = form.FindSingle(Of Ranorex.Button)(".//button[@controlid='92']")   
  button.Click()   
  
  button = form.FindSingle(Of Ranorex.Button)(".//button[@controlid='133']")   
  button.Click()   
  
  button = form.FindSingle(Of Ranorex.Button)(".//button[@controlid='121']")   
  button.Click()   
Catch e As RanorexException   
  Console.WriteLine(e.ToString())   
  returnError = -1   
End Try  
Return returnError  

Build and start the application by pressing F5.

C opyright © 2012 Ranorex

Page 232 of 247


System Requirements
Supported Operating Systems

All versions (32 and 64 bit, except those for Itanium-based systems) of the following operating systems are
supported by Ranorex:

Windows 2000 (Ranorex Studio not available)


Windows XP
Windows Server 2003
Windows Vista
Windows Server 2008
Windows 7

Software Prerequisites
The following software prerequisites are required to run all Ranorex components (Runtime, Spy, Recorder,
License Server). All needed prerequisites are usually automatically installed when running the Ranorex setup:

Microsoft Windows Installer 3.1 or higher


Microsoft Visual C ++ 9.0 x86
Microsoft Visual C ++ 9.0 x64 (required for 64 bit Windows versions only)
Microsoft Visual C ++ 10.0 x86
Microsoft Visual C ++ 10.0 x64 (required for 64 bit Windows versions only)
Microsoft .NET Framework 2.0 SP2 or higher

Additionally, for running Ranorex Studio the following prerequisites are required:

Microsoft .NET Framework 3.5 SP1 or higher

Hardware Requirements

The hardware requirements depend on the version of the .NET Framework that needs to be installed for the
respective Ranorex package. Ranorex (Runtime, Spy, Recorder, License Server) requires at least the .NET
Framework 2.0 to be installed, Ranorex Studio requires the .NET Framework 3.5. C onsequently:

The minimum system requirements for running Ranorex (Runtime, Spy, Recorder, License Server) are the same
as those for the .NET Framework 2.0:
http://msdn.microsoft.com/en-us/library/ms229070.aspx
The minimum system requirements for running Ranorex Studio are the same as those for .NET Framework 3.5:
http://msdn.microsoft.com/en-us/library/bb882520.aspx

Ranorex License Server Firewall Configuration


On a system running Ranorex License Server the firewall must be configured to allow access to TC P and UDP port
7266.

C opyright © 2012 Ranorex

Page 233 of 247


64-bit Platforms
Ranorex handles testing of 32/64 bit based applications on 64 bit operating systems automatically. It is possible,
but recommended only for advanced users, to turn off the bit bridge feature within the Ranorex Settings dialog.

If you disable the bit bridge feature (not recommended!) or your Ranorex version does not support
the bit bridge (versions prior to V2.3), follow these guidelines to make 32/64 bit automation
interoperable:

On 64 bit versions of Windows processes may run using 64 bit or 32 bit (also called “x86”) architecture.
Applications that are started as 32 bit processes are marked with “*32” in the Windows Task Manager, all others
use the 64 bit architecture.

Task manager showing 64 and 32


bit calclulator application

Ranorex can as well run as a 32 bit or 64 bit process, both versions are included in the setup. In general, one
should use the Ranorex version that matches the bit architecture of the automated application. I.e. if you
automate a 32 bit application, use "Ranorex Spy (32bit)" (formerly "Ranorex Spy (x86)") and "Ranorex Recorder
(32bit)" (formerly "Ranorex Recorder (x86)"), otherwise use "Ranorex Spy" and "Ranorex Recorder" (64 bit
versions).

Ranorex start menu folder on a 64 bit


environment

When you compile your own Ranorex executables, be sure to specify the right target architecture in your project
settings. In Ranorex Studio this setting is on the “C ompiling” tab in the project properties. .NET applications are
by default started as 64 bit processes on 64 bit operating systems unless the target C PU is explicitly set to the 32
bit (x86) architecture. C onsequently, set the “Target C PU” property to “Any processor” for automating 64 bit
applications and to “32-bit Intel-compatible processor” for 32 bit applications.

Page 234 of 247


Ranorex Studio - advanced compiler settings

C opyright © 2012 Ranorex

Page 235 of 247


Remotely Working with Ranorex
This section will give information on how to successfully record and replay Ranorex Test Scripts on remotely
connected machines.

Do not Automate via Remote Desktop Window


Do not C lose or Minimize the RDP Window
Disable Mouse/Keyboard Activities
Use same C olor and Resolution Settings
Increase Timeouts on Virtual Machines
Disable Asynchronous Dispatching of Mouse and Keyboard Events

Do not Automate via Remote Desktop Window


The first important thing to know is that Ranorex, as every other automation software, is not able to automate via
the Remote Desktop window. It is not possible to recognize any controls since the content of the remote desktop
is only provided as one big image.

The only way to automate using the Remote Desktop window to work coordinate based or with image
comparison. This is not recommended by Ranorex because minimal variances in your system will make your
tests fail.

To guarantee successfully testing on remote machines, you have to install and start all Ranorex Tools you need
on the remotely connected machine.

Do not Close or Minimize the RDP Window


Remote Desktop locks the screen when you minimize or close the Remote Desktop window. That causes
screenshots to be blank/black and automation to fail. C onsequently, if you use Remote Desktop, you need to
have the RDP window open during automation and not closed or minimized.

Also make sure that the screensaver is not activated on your remotely connected machine as the screensaver
will also lock the Remote Desktop’s screen.

As a workaround, you can set up one machine having all of your Remote Desktop windows opened. This machine
does not do any automation. And while your tests are running on the different Remote Desktops – with the client
windows opened on the mentioned machine – you can lock the desktop on this machine. While your client
desktop is locked, the Remote Desktop sessions will remain opened and your test will continue.

An alternative to RDP is using VNC or the VMWare Remote C onsole as these tools will not lock the screen when
closing or minimizing the remote client window.

Disable Mouse/Keyboard Activities


As an alternative to locking the screen on your Remote Desktop, you can disable the physical mouse and
keyboard on the remote machine. To do that just set the Ranorex Keyboard.Enabled and Mouse.Enabled
properties to false. Be careful if you disable both keyboard and mouse because both devices will stay disabled
until you set the Enabled property back to true or the automation process ends!

If you want to disable the input for the whole test cycle, you should set

C#
view plain c opy to c lipboard print

Keyboard.Enabled = false;  

and

Page 236 of 247


C#
view plain c opy to c lipboard print

Mouse.Enabled = false;  

in the Program.cs file.

But again be careful when using these properties because when you set both to false you cannot abort the test
without an AbortKey set.

So also set

C#
view plain c opy to c lipboard print

Keyboard.AbortKey = System.Windows.Forms.Keys.Pause;  

in Program.cs to abort the test if something unexpected (e.g. an endless loop) happens.

You can also use this technique for one recording only. In this case you have to enable/disable the mouse and
keyboard controls in user code directly before executing specific actions. As always, don't forget to enable
controls again at the end of your recording and to set an AbortKey.

Use same Color and Resolution Settings


If you perform image based automation/validation on remote machines, you have to make sure that color and
resolution settings are the same as on the machine you made the test/recording on.

Please also make sure that you have activated the same windows scheme since your application under test might
be displayed differently when having different schemes activated.

Increase Timeouts on Virtual Machines


Things might run a little slower on a virtual machine compared to real machine because multiple virtual machines
may share the same physical host. C onsequently it can take more time on a Virtual Machine to find some
elements. You may need to increase repository timeouts for specific elements or alter your tests to check for
ready states on your application under test. It's recommended to use the global timeout factor to adapt the
timeouts for a specific test run.

Disable Asynchronous Dispatching of Mouse and Keyboard Events


Using Ranorex Tools on a remote machine connected with RDP might make the mouse pointer start wobbling
sometimes. In that case try to disable the "Use asynchronous dispatching of mouse and keyboard events" option
in the configuration's general tab page.

Page 237 of 247


Use asynchronous dispatching of mouse and
keyboard events option

This should fix the shaking mouse behavior.

C opyright © 2012 Ranorex

Page 238 of 247


Silent Installation of Ranorex
You can use standard MSI command line arguments (see below for examples) to customize the Ranorex
installation, for example, to install the Ranorex Runtime silently on different (virtual) machines.

Installation Packages
Installation C ommand Line Arguments
Install Ranorex License

Installation Packages
Ranorex uses the Microsoft/Windows Installer (MSI) for its setup. C onsequently, all standard MSI command line
arguments can be used. The command line arguments work both with the self-extracting zip file ("Ranorex-
x.x.x.exe") and the "setup.exe" and "Ranorex-x.x.x.x.msi" files contained in the "Ranorex-x.x.x.zip" file.

System administrators may use the Ranorex MSI package for installation. You can download the "Ranorex-
x.x.x.zip" containing the MSI package from our homepage; the download link is the same as for the self-
extracting zip file ("Ranorex-x.x.x.exe"). Just replace the file ending "exe" with "zip".

When installing Ranorex using the MSI package you have to make sure that all Ranorex prerequisites are
installed before executing the MSI package (please see the "README.txt" included in the ZIP archive or the
Ranorex system requirements). If you are unsure, please use the "setup.exe" or self-extracting zip file "Ranorex-
x.x.x.exe" to start the installation, which will also install all required prerequisites.

Installation Command Line Arguments


To install Ranorex silently, pass the "/quiet" (no UI) or "/passive" (progress bar only) command line argument:

msiexec /i Ranorex-x.x.x.x.msi /quiet


or: setup.exe /passive
or: Ranorex-x.x.x.exe /quiet

If you do not want to install all Ranorex features you can (de)select these features using the command line
options "ADDLOC AL" and "REMOVE".

For example, the following command line will install all Ranorex components except for Ranorex Studio:

msiexec /i Ranorex-x.x.x.x.msi ADDLOCAL="ALL" REMOVE="RanorexStudioFeature"


or: Ranorex-x.x.x.exe ADDLOCAL="ALL" REMOVE="RanorexStudioFeature"

Possible feature names used as parameter to ADDLOC AL or REMOVE (separated by commas) are:

“MainFeature” (C ore components)


“RanorexSamples”
“RanorexStudioFeature”
“RanorexFirefoxExtension”
“RanorexIEAddon”

For more installation options see the help for the MsiExec program by typing ("/v" is needed for the "*.exe" files):

msiexec /help
or: setup /v /help
or: Ranorex-x.x.x.exe /v /help

Install Ranorex License


To finish your silent installation you have to install a valid license.

If you’d like to install a floating license you have to copy the file Ranorex3_Server.lic (for Ranreox3.x
installations) or Ranorex2_Server.lic (for Ranorex 2.x installations) into the folder “%ALLUSERSPROFILE%” by
using the "XC OPY" command in a batch file. The file will be created when you first install a License Server license
Page 239 of 247
on a Ranorex C lient. Just search for that file on a client machine running a floating license.

If you’d like to install a node locked license you have to generate a license file. The web address used to
authenticate the license key is part of the licensing email delivered after purchasing licenses. Simply open a
browser, navigate to the authentication page and enter your license key and the machine's host name into the
respective fields. After clicking the 'Authenticate' button you will be able to download the license file. Rename the
downloaded file to Ranorex3.lic (for Ranreox3.x installations) or Ranorex2.lic (for Ranorex 2.x installations) and
copy it to the folder “%ALLUSERSPROFILE%” by using the "XC OPY" command in a batch file.

C opyright © 2012 Ranorex

Page 240 of 247


Licensing
In general Ranorex provides two different types of licenses to install:

Node Locked User License


C oncurrent Floating User License

The node locked license type is bound to the machine's host name. After registration each license can be used
perpetually on the registered machine. A floating user license can be shared between different machines, but can
only be used by one machine (and user) at a time.

Both license types are available for Ranorex Runtime, Professional, and Premium Edition.

License Registration
In order to register a Ranorex license, start the Ranorex Licensing tool, which is available in the Ranorex start
menu folder.

License installation dialog

The license installation tool is used to install both types of licenses.

Installing a Node Locked License


To install a machine-bound Ranorex license select the 'Use Machine License' option. Though the license needs to
be activated on the Ranorex server over the internet, it is not necessarily required to have an internet connection
available on the target machine.

Installing with Internet Connection


Simply type or paste in the Ranorex license key which is part of the which has been delivered to you by email
and press 'Install'.

Page 241 of 247


Installed license after activation

Note: The "Transfer License" button is used to prepare your license for transferring from one machine to
another.

Installing license without Internet Connection


If there is no internet connection available Ranorex allows to register the target machine using a license
activation web site on a computer with an internet connection.

Error Dialog - "No internet connection available"

The web site adress used to authenticate the license key is part of the licensing email delivered after purchasing
licenses. Simply open a browser and navigate to the authentication page. Fill in your license key and the
machine's host name. After clicking the 'Authenticate' button you'll be able to download the license file. Load the
downloaded file within the Ranorex licensing tool in order to finish the license installation process on the target
machine.

License authentication using


Ranorex web site

Installing a Floating License

Installing and configuring the Ranorex License Server


Page 242 of 247
In order to use a Ranorex Floating License it is required to install and run the Ranorex license server application
on a computer (server) within a network. The download link for the license server setup package is part of the
license delivery email. Simply install the package on a system which is reachable from computers which intend to
use a Ranorex floating license.

Note: To prevent firewalls from blocking communication between license server and client, it is required to open
port 7266 for TC P and UDP access on the server.

Note: By installing a Ranorex license server it's required to use a Ranorex license server installation package
which is at least as actual as your Ranorex client installation.

License server dialog - one premium licenses in use

Open the Ranorex license server configuration tool. Add the floating license keys to the text box and press
'Install'. These licenses are now ready to use.

Note: It is recommended to have an internet connection available in order to install a new license. 

No internet connection available - license needs to


be registered on a computer with internet
connection

If there is no internet connection available authenticate the floating license using the license authentication web
site. The web site adress used to authenticate the license key is part of the licensing email delivered
after purchasing licenses. Simply open a browser and navigate to the authentication page. Fill in your license key
and the machine's host name. After clicking the 'Authenticate' button you'll be able to download the license file.
Load the downloaded file within the Ranorex licensing tool in order to finish the license installation process on the
target machine.

Configuring Developer and Runtime Clients

In order to use an installed floating license, open the Ranorex license tool on the client and select the option "Use
License Server".

Page 243 of 247


Using license server for Ranorex Premium edition

Press the button 'Detect' to request a list of the currently available license servers within the local network.

The license type specifies which license (Runtime, Professional, Premium) should be used on the client. By
selecting 'Auto', the client automatically requests the appropriate license. In case of running Ranorex tests
without starting any Ranorex tool, only a Runtime floating license will be used. When starting Ranorex Spy tool a
Professional floating license will be leased on the server. After pressing the 'Install' button the client is assigned to
the selected license type. To switch the currently installed license type, simply select another one from the list
and click 'Install' again.

Every time a Ranorex test, a Ranorex tool, or Ranorex Studio is started the client sends a license request to the
server. If the type of the required license is available, it will be assigned to the requesting client. By closing
Ranorex Studio or finishing a test run the license will be automatically released and can then be used by other
clients.

C opyright © 2012 Ranorex

Page 244 of 247


FAQ
How does Ranorex identify UI elements?
Is it possible to run the same Ranorex test code on Vista and XP?
Is it required to use RanoreXPath for test automation?
Does Ranorex support data driven testing?
What to do when items can't be found during Ranorex test execution?
Is it possible to extend recordings with user specified code actions?
What is the difference between Adapter and Element?
Is it possible to trigger Ranorex tests from an existing test or build environment?
C an I use Ranorex libraries within Visual Studio?
What shall I do with unexpected dialogs and popup windows during test automation?
Is it possible to test Silverlight applications with Ranorex?
Is it possible to automate a webpage without moving the mouse pointer?
What are the system requirements for developing and running Ranorex tests?

How does Ranorex identify UI elements?


Ranorex uses the RanoreXPath to identify applications and their UI elements required for test automation. The
RanoreXPath provided by Ranorex Spy consists of many different, technology dependent attributes which can be
modified and adapted by the user. To separate test code from identification information Ranorex provides a
repository to map logical names to RanoreXPath expressions. 

Is it possible to run the same Ranorex test code on Vista and XP?
Yes. All identification information is stored within a RanoreXPath expression and is therefore separated from the
test automation code. The following RanoreXPath expression finds a button both on Windows XP and on Windows
Vista:

/form[@title='WordPad']/.//button[@text='&No' or @text='Do&n''t Save']

The RanoreXPath searches for a button, whether it contains the text '&No' or ''Do&n't Save'.

Is it required to use RanoreXPath for test automation?


No. It's also possible to search for GUI elements or forms using a number of different 'Find' methods to search
and/or filter for child elements.
Have a look at the code example of the online documentation to see how it works.
http://www.ranorex.com/support/user-guide-20/test-automation-code-examples.html

Does Ranorex support data driven testing?


Yes. Ranorex supports four different data connectors to build data driven test cases: 

Simple Data C onnector


SQL C onnector
C SV File C onnector
Excel C onnector

A general description of how to create data driven test cases can be found here:

Lesson 3: Data-Driven Testing

What to do when items can't be found during Ranorex test execution?


Page 245 of 247
What to do when items can't be found during Ranorex test execution?
There are two primary reasons why some items can't be found during replay:

1. Search timeout: Each element and each folder stored within the objects repository defines is it's own
timeout used for search. In many cases it is required to wait for a dialog before continuing automation.
Use the 'SearchTimeout' property to define the maximum time to search for the specified element.
2. Wrong RanoreXPath: Start the application under test and make sure that the relevant GUI object is
visible. C heck the object's RanoreXPath within the repository browser using the 'Highlight Element' context
menu item to see if Ranorex can find the element. Open Ranorex Spy to track the specified GUI object
again. C ompare the absolute path, shown within the object repositorie's property grid, with the given
RanoreXPath provided by Ranorex Spy. If the given path by Ranorex Spy differs from the path
represented by the repository use the path from Spy to the repository.

Is it possible to extend recordings with user specified code actions?


You can easily extend standard recordings with user specific code actions by converting existing action items or
by adding a new user code action item to a recording. Learn more about hwo to use user code actions in
recordings here: Lesson 5: User C ode Actions

What is the difference between Adapter and Element?


Adapters provide an easy-to-use interface for accessing attributes and actions of elements. Each item generated
by the Ranorex object repository automatically represents a Ranorex Adapter (Button, C heckBox, Text, LitsItem,
TreeItem, ...). You can only create a Button Adapter of an element if the element supports the Button role, i.e. if
RanorexSpy recognizes the element as a Button.
If your controls are recognized as "Unknown" or "Element", Ranorex cannot assign them a role. You can't use
special attributes or actions with these elements, but you can usually still create a path that identifies the element
to execute minimally mouse clicks.

Is it possible to trigger Ranorex tests from an existing test or build


environment?
The result of a Ranorex test automation project is always an executable file. The generated *.exe can easily be
started from other environments supporting command line execution.

Can I use Ranorex libraries within Visual Studio?


That's one of the big advantages of using Ranorex. You're able to use your existing development environment to
develop Ranorex based test automation code. Additionally the code generated by the Ranorex Recorder or
Ranorex Repository can easily be integrated into your Visual Studio projects. Read more ...

What shall I do with unexpected dialogs and popup windows during test
automation?
Ranorex recognizes and specifies whether an application still has the top level characteristic or not. In case of
totally unexpected dialogs, the Ranorex.Report class provides a simple way to log screen shots of the current
desktop status. Read more about how to handle popup dialogs within Ranorex test auotmation code:
http://www.ranorex.com/support/user-guide-20/test-automation-code-examples.html#c3328

Is it possible to test Silverlight applications with Ranorex?


Yes it is. Simply ensure that your Silverlight application does not run in window-less-mode, i.e. set the
'Windowless' property of the Silverlight HTML object to false. Find more information about window-less mode on
the following site: msdn.microsoft.com/en-us/library/cc838156(VS.95).aspx

Is it possible to automate a webpage without moving the mouse pointer?


Yes it is. Simply use the 'PerformC lick' instead of the normal 'C lick' method when working with web adapters like
'DivTag', 'Input' or 'Link'.

What are the system requirements for developing and running Ranorex
Page 246 of 247
tests?
The following link to our online documentation shows what is needed to develop or to simply run Ranorex tests.
C lick here ...

C opyright © 2012 Ranorex

Page 247 of 247