Вы находитесь на странице: 1из 37

Version2.

Tutorial

1 Ranorex General Overview ................................. 3
Ranorex Philosophy ....................................................................................... 3
Ranorex Automation Framework ..................................................................... 4

2 Object recognition with Ranorex ............................. 5


Working with Ranorex Spy ............................................................................. 5
How to track elements with Ranorex Spy ..................................................................................... 5
Tracking of menu items ................................................................................................................. 6
Tracking Result What to do with the tracked information? ....................................................... 6
RanoreXPath editor box ................................................................................................................ 8

3 Ranorex Studio Part I ...................................... 12


Creating a first test executable ..................................................................... 12
Capture and Replay of User Actions ............................................................................................ 14

4 Ranorex Recorder Capture/Replay Editor ............. 17


Separate Automation from Identification The Ranorex Repository .................... 17
Code behind the Recorder Design View ......................................................... 19
How to extend and modify existing Recordings ................................................ 19
Simple Actions ............................................................................................................................. 19
User Code ..................................................................................................................................... 20
Recorder Configuration ................................................................................ 22
Repository Configuration .............................................................................. 25
Data Driven Recordings ............................................................................... 28

5 Ranorex Studio Part II ..................................... 31


Ranorex Automation Library ......................................................................... 31
Using the Ranorex Repository in code ........................................................................................ 31
Working without Ranorex Repository ......................................................................................... 32
Failure Handling, Exceptions and Report generation ......................................... 34
How to handle unexpected dialogs................................................................. 35
How to organize a test automation project with Ranorex Studio ......................... 36
Running compiled executable........................................................................ 37
Chapter 1 | Ranorex General Overview

1 Ranorex General Overview


Ranorex Philosophy

Ranorex workflow

One of the major goals of Ranorex is to bring developers and testers together to real-
ize professional test automation projects. This is only possible by providing both
groups with the appropriate tools and functionality. The Ranorex Automation Library
can be seen as a core component of Ranorex, which is needed for every automation
task executed by Ranorex. For Testers with less programming experiences, we rec-
ommend using Ranorex Studio in combination with Ranorex Recorder to create auto-
mated test modules. More experienced developers can also use the Microsoft Visual
Studio environment to implement their test automation tasks. This allows for more
complex test modules to be created by the developers before releasing their code for
integration tests and for the testers to integrate these modules within the Ranorex
Studio environment into comprehensive test suites.

Regardless of who or which way a test is implemented, test scripts are compiled to
standard executable files or libraries which perform the automated test. This allows a
flexible use to deal with existing test management environments.

Ranorex Tutorial 3
Chapter 1 | Ranorex General Overview

Ranorex Automation Framework


The Ranorex Automation Framework consists of the following components:

Ranorex Automation Library


Ranorex Tools
Ranorex Studio

Ranorex Components

The Ranorex Automation Library is the core component used not only for test au-
tomation, but also used by all other Ranorex tools. The library is based on the .NET
framework, and is therefore easy to integrate into existing development environments.

The Ranorex Standalone Tools can be used for different scenarios. While the Rano-
rex Recorder is often used to create quickly short test automation tasks with cap-
ture/replay, Ranorex Spy provides you with information about the GUI elements which
are accessible for automation. The Ranorex Repository manages all objects and Rano-
reXPath expressions are required for further test automation.

Ranorex Studio integrates all these tools into a test development environment which
provides additional features for code editing, code completion, and debugging functio-
nality.

Ranorex Tutorial 4
Chapter 2 | Object recognition with Ranorex

2 Object recognition with Ranorex


Working with Ranorex Spy
As a standalone tool, Ranorex Spy provides all the functionality needed to explore and
analyze applications or websites - including all their controls and GUI elements. After
starting Ranorex Spy, the element browser contains information about all currently
running applications on the Windows desktop.

Ranorex Spy - applications and their UI elements

How to track elements with Ranorex Spy

Ranorex Spy provides two ways to track GUI elements from an application.

Track the elements using the 'Track' button or


Use the instant tracking short cut <CTRL>+<LWin>

Click the 'Track' button to start tracking a GUI element. Move your mouse pointer over
a specific control (button, text box) so that the currently identified object is hig-
hlighted. By clicking the control the tracking mode will be stopped and all information
of the selected GUI element will be shown within Ranorex Spy.

Ranorex Tutorial 5
Chapter 2 | Object recognition with Ranorex

Click 'Track' button to start element tracking

In some cases it might be necessary to track GUI elements which are currently behind
the Ranorex Spy window. Simply uncheck the 'Always On Top' checkbox causing Ra-
norex Spy to minimize during the tracking process.

'Always On Top' checkbox within Ranorex Spy

Tracking of menu items

When tracking menu or popup items you have to use the Instant Tracking method by
using a short cut to select a GUI element. Simply move your mouse pointer over a
menu item and press the <CTRL> + <LWin> key combination to instantly track the
GUI element. Instant Tracking is not only available for popup items. This tracking
mode can also be used for all other GUI elements and is also provided by the Ranorex
Repository browser.

Tracking Result What to do with the tracked information?

After tracking an GUI element, Ranorex Spy shows different types of information
available for the proper element:

RanoreXPath Identification string


Available attributes and properties for validation during testing
Graphical information
Extended information about the used adapters or other Ranorex specific proper-
ties

Ranorex Tutorial 6
Chapter 2 | Object recognition with Ranorex

RanoreXPath

Ranorex Spy is mostly used to determine which RanoreXPath should be used to identi-
fy a UI element. After tracking an element, the RanoreXPath is shown in the RanoreX-
Path editor box. The RanoreXPath is one of the most important parts of the Ranorex
test automation framework. Every Ranorex test automation task uses RanoreXPath
expressions to identify controls like text boxes or buttons.

The RanoreXPath syntax is based on XPath and can not only be used for identification,
but also for searching and filtering of multiple elements. Read more about RanoreX-
Path syntax in the Ranorex User Guide.

Available attributes and properties for validation during testing

All the information shown in the General tab is accessible during automation and can
be used when desired within a RanoreXPath expression.

Available Ranorex Adapters for a WinForms button

In addition to the General properties like Valid or Enabled Ranorex provides different
adapters allowing not only access to e.g. button-related properties but also to use
technology dependent information, e.g. .NET control attributes like the ControlName
value. In fact, there are two big groups of adapters:
Logical Adapters such as like Button, Text, ListItem, Tree,
Technology-dependent adapters like Control for .NET WinForms, or Native-
Window for Win32 controls

Ranorex Tutorial 7
Chapter 2 | Object recognition with Ranorex

More information about how to use the different adapters during test automation with
Ranorex is described in section number 5.

RanoreXPath editor box

Each element within the Ranorex Spy tree is identified through the RanoreXPath ex-
pression shown in text box.

Ranorex Spy shows tracked information from button Add

This automatically generated RanoreXPath shows only one way to identify an object
uniquely. But it is not required to use the suggested path. You can also modify parts of
the RanoreXPath expression, or rewrite the whole path string from scratch to query for
an element in the Ranorex Spy tree.

To support editing of RanoreXPath expressions, the editor textbox provides an auto


completion feature, which should help to avoid syntax errors and to accelerate writing.

Lets create an example path with Ranorex Spy to explore the possibilities of the Rano-
reXPath editor box:

1. Start the Ranorex Spy tool and track the Add button of the VIP Sample-
Application.

Ranorex Tutorial 8
Chapter 2 | Object recognition with Ranorex

The automatically generated RanoreXPath expression is shown in the editor box.

2. Now change the last part of the expression by deleting the


@controlname=btAdd within the brackets.

Set the cursor between both brackets and press the key combination
<CTRL><SPACE> to activate auto completion.

The auto completion shows the next options to go further in specifying the Rano-
reXPath. Select the @ sign to introduce an attribute comparison.

3. Press the key combination <CTRL><SPACE> again to see which attributes for
the button object are available.

Note: All of the available attributes listed in the drop down box are shown in the
overview tab of Ranorex Spy as described above.

Select the text attribute to do the identification based on the text value property
of the button and press the auto completion key combination.

Select the equal sign and continue again with the key combination
<CTRL><SPACE>.

Now, finish the RanoreXPath by selecting the Add string value, and press enter
to query the Ranorex Spy tree. The new RanoreXPath expression should find the
same button as before. After pressing the Enter key the editor box switches to
RanoreXPath edit mode to filter for UI elements.

Ranorex Tutorial 9
Chapter 2 | Object recognition with Ranorex

A RanoreXPath expression could also match multiple items as the following


screenshot shows.

This mechanism helps to filter for UI elements within an application and to trans-
fer the result directly into a repository file using the context menu item Add
Matching Children to Repository.

Ranorex Tutorial 10
Chapter 2 | Object recognition with Ranorex

Note that Ranorex always tries to create a path which provides a unique, but ro-
bust identification of the element in question.

Ranorex Tutorial 11
Chapter 3 | Ranorex Studio Part I

3 Ranorex Studio Part I


The Ranorex Studio integrates all Ranorex tools for building test automation solu-
tions. It provides all necessary functionality required for test automation development.

Creating a first test executable


The next example describes how to create an first initial Ranorex Studio project, which
includes one simple test for the VIPDatabase application. We will also generate a sim-
ple executable for the test to see how the test could be executed externally.

First, we start Ranorex Studio and create a new project by selecting the menu item
('File '| 'New' | 'Solution...')

Creating a new Ranorex Studio project

Now, select the 'Ranorex Console Application' template from the category 'C#' and
choose a name for your project.

Ranorex Tutorial 12
Chapter 3 | Ranorex Studio Part I

After clicking the 'Create' button, the new Ranorex project will be opened.

Ranorex Studio main regions

The Ranorex Studio IDE is devided into 3 main regions:

Ranorex Studio Project Explorer


File View Panel
Element Browser

Project Explorer

The project explorer shows all files and folders, which are currently part of the Ranorex
Studio project file. In the case of a simple Ranorex C# console test project, the project
tree contains a basic source file (Program.cs), an empty recording (Record-

Ranorex Tutorial 13
Chapter 3 | Ranorex Studio Part I

ing1.rxrec), and an empty repository file (RxTraining_01_Repository.rxrep). In addi-


tion the explorer allows adding any type of file-like documents, simple CSV files or
creating folders which might be needed within the project.

File View Panel

By double-clicking one of the files listed in the project explorer, Ranorex Studio opens
the file in the file view panel. Ranorex Studio also shows external files using the File |
Open menu item.

Element Browser

By clicking the Element Browser tab at the bottom of the Project Explorer, the inte-
grated Ranorex Spy will be activated.

Ranorex Spy represented within the Element Browser tab of Ranorex Studio

Capture and Replay of User Actions

Next, we start the VIP Database application, which were going to test with Ranorex.
This is the description of the test case we will automate with the recorder:

1. Add a new VIP with the first name John and a last name Smith
2. Select the Male radio button of the gender group box.
3. Select the Music item of the category list box.
4. Click the Add button.
5. Validate the text of the status box
6. Select the added VIP and delete the item from the list

Ranorex Tutorial 14
Chapter 3 | Ranorex Studio Part I

Next, start now Ranorex Recorder and perform each step in the GUI application ma-
nually. The running recording session is indicated through the Recorder toolbar, which
allows you to do some validation during the recording, to pause the recording, or to
stop the recording.

Ranorex Recorder toolbar

After recording the actions, the Recorders action table should contain each manually
performed step.

Recorded actions listed within the Recorders actions table

Simply click the PLAY button to replay all of the just recorded actions. After the rep-
lay, Ranorex Studio automatically creates a file containing a report of the performed
actions.

Ranorex Tutorial 15
Chapter 3 | Ranorex Studio Part I

Ranorex Report file generated after replaying the recording

Until now we have only replayed the recorded actions directly within Ranorex Record-
er. By building the project the compiler generates the executable within the default
output folder. To build the project select the menu item Build | Build <ProjectName>
or press the short cut key <F8>.

The output box notifies that the build process was finished successfully

To start the test externally, simply open the project folder and open the directory
bin\debug which contains the test executable.

Ranorex Tutorial 16
Chapter 4 | Ranorex Recorder Capture/Replay Editor

4 Ranorex Recorder Capture/Replay Editor


Ranorex Recorder is used to record and replay the users keyboard and mouse actions
during a manually executed test of the user interface. In addition the Recorder can va-
lidate current states and properties like Text or Visibility of GUI elements. The Re-
corder is a capture replay editor which is available both as stand-alone tool and as an
integrated editor within Ranorex Studio.

Separate Automation from Identification The Ranorex Repository


When we look at the previous recording, we see that the Recorder view is divided into
an action table and an object repository. The action table contains all recorded mouse,
keyboard or validation actions. The object repository is used to identify all objects re-
quired by each recorded action item.

Separation of actions and RanoreXPath identification information

Within Ranorex Studio, the repository is also part of the project and is represented as
*.rxrep file. Each Ranorex repository represents mapping information and targets to
centralize GUI element identification information for easier maintenance. There is no
need to change test automation modules when names or other identification attributes
within the application under test change. Instead, these changes are made within the
associated repository.

Repositories can contain the following types of items:

Ranorex Tutorial 17
Chapter 4 | Ranorex Recorder Capture/Replay Editor

Ranorex Repository within Ranorex Spy tool

Application folder #1 Represents a top level application, dialog or web site


Represents a Ranorex adapter (Button, ListItem, Text-
Adapter item #2
Box, ComboBox,...)
Normal folder #3 Used to organize items
Contains GUI elements which have the same parent or
Rooted folder #4
RanoreXPath prefix (optional)

Now, we adapt the automatically generated repository by changing some logical


names and by adding a folder called InputFields.

Modified repository

Ranorex Tutorial 18
Chapter 4 | Ranorex Recorder Capture/Replay Editor

After we have changed the logical names and the structure of the repository, the re-
cordings action table gets updated automatically with the new item names.

Code behind the Recorder Design View


Every time a recording changes, Ranorex Studio automatically renews the code for all
actions in the associated Recording.cs file.

Code behind the recording

Simply open the recorder generated code by selecting the View Code toolbar but-
ton, or by opening the C# file directly, using the Project Explorer. As you can see, the
code is also based on the repository. Therefore, its very easy to understand what the
code does as long as the repository is well organized.

How to extend and modify existing Recordings


Each recording can be extended by simple actions like mouse clicks, additional valida-
tions or report log entries. But, it is also possible to extend the recording with user
specific code, or to call special methods provided by other testing projects.

Simple Actions

What we do first is to extend the existing recording with an additional validation at the
beginning of the recording to check the Enabled property of the Delete button.

1. Select the first action item of the recording and click the Add validation item
button on the recorders toolbar.

Add a new validation item

2. The recording now contains an empty validation action which does not refer to
any of the repository items.

Ranorex Tutorial 19
Chapter 4 | Ranorex Recorder Capture/Replay Editor

New and unlinked action item

3. Simply click the cell with text (no repository item) to select the Delete button
from the repository.

Associate Delete button to validate

4. Then select the property Enabled to check the state with the value False

Select attribute Enabled to check

5. Press the PLAY button to see the result of the additional validation in the re-
port view.

User Code

The recorder IDE provides some common, simple actions through the toolbar. But, in
some cases it might be helpful to adapt the automatically generated code with some

Ranorex Tutorial 20
Chapter 4 | Ranorex Recorder Capture/Replay Editor

user specific validation. Lets do a first small adaptation on the second key sequence
action:

Converting key sequence action item into user code item

Use the context menu item Covert to User Code Item to outsource the code line from
Recording1.cs file to Recording1_UserCode.cs file. Also specify a name for the method
as follows:

Specifying method name for user code item

After saving the current recording use the View Code context menu item to open the
Recording1_UserCode.cs file and change the content of the method MyMethod into
the following:

/// <summary>
/// The Recording1 recording.
/// </summary>
public partial class Recording1
{
static Recording1()
{
//Your recording specific initialization code goes here.
}

public static void MyMethod()


{
//Your code here.
//Code inside this method will not be changed by the code
generator.
string lastName = "Meyer";
Keyboard.Press(lastName);
}
}

By converting an action item to a user code item, Ranorex simple copies the code line
used in the automatically generated Recording1.cs file to the user defined method lo-

Ranorex Tutorial 21
Chapter 4 | Ranorex Recorder Capture/Replay Editor

cated in the Recording1_UserCode.cs file. Also the recording code now uses that me-
thod instead of the initial code to execute the user code action.

The key sequence is now replaced by calling the user method MyMethod()

To execute the code the Ranorex Studio project needs to be compiled. Also we need to
ensure that the created recording is triggered from the main routine of the Ranorex
Studio project.

Open the Program.cs file to see if the Start() method of the Recording is called cor-
rectly.

Start the Recording1 within the main method of Program.cs file

Click now the play button of the Ranorex Studio toolbar (not of the Recorder) to re-
compile the project and to start the generated executable directly after building the
project.

Recorder Configuration
Each recorded action is generally specified by an action type (Click, Validation ), and
an associated repository item specifying the target of the action to perform. In addi-
tion to that, there are various other properties available for tuning each action.

Ranorex Tutorial 22
Chapter 4 | Ranorex Recorder Capture/Replay Editor

Item related properties available for each action

The property view in Ranorex Studio shows all of the available properties related to
the currently selected item within the recording. If the property view is not visible,
simply use the context menu item, Properties, to open the Properties view.

It is also possible to preconfigure the Recorders behavior by specifying what should be


recorded during a recording session or how it should be replayed afterwards. Simply
click the Configuration toolbar button within the Recorder to open the configuration
dialog.

General Settings

The general settings are not only related to the Recorder's behavior, but also to how
the Repository generates its object items.

Use the Use Ensure Visible by default checkbox to specify the default value for each
automatically generated repository item. This setting causes Ranorex to ensure the vi-
sibility of an element on the GUI, before an action like a simple mouse click will be ex-
ecuted on it.

You can also increase maximum length of text values used within RanoreXPath ex-
pressions to ensure uniqueness for long attribute values, especially for form titles.

Current Recording

Ranorex Tutorial 23
Chapter 4 | Ranorex Recorder Capture/Replay Editor

This tab primarily contains configuration parameters for code generation specific to the
current recording. Additionally it provides a check box to turn on the generation of
replay reports. These settings are stored within each recording.

Recorder Defaults

The 'Recorder Defaults' tab allows configuration of user-specific global default values.
A default namespace for code generation can be defined here or the recorder can be
instructed to record relative coordinates for each mouse action.

Additionally, the default values for mouse move time, keyboard-related action time, or
duration time of manually added mouse actions, can be defined here. There is also a
setting available to specify when the Recorder should split key sequences into smaller
ones. These settings are stored globally and valid for each newly created recording.

The replay and code generation settings also affect the generated code:

Ranorex Tutorial 24
Chapter 4 | Ranorex Recorder Capture/Replay Editor

// represents the default values


// within configuration dialog
Mouse.DefaultMoveTime = 300;
Keyboard.DefaultKeyPressTime = 100;
// represents the recordings speedfactor
Delay.SpeedFactor = 3.0;

// if the current replay speed


// is set to Turbo mode ...
Mouse.DefaultMoveTime = 0;
Keyboard.DefaultKeyPressTime = 20;
// Represents the recordings speedfactor
Delay.SpeedFactor = 0.0;

Repository Configuration
Each item of the repository used by the recording, provides additional properties to
specify how to search for the element before performing the associated action, which
is specified in the Recorders actions table.

Item related properties for each repository item

The most important setting of a repository item is the Search Timeout property,
which specifies the maximum time spent to search for the element in question.

The following Ranorex exception reports that the specified element for the given Rano-
reXPath was not found within the specified timeout. Check the validity of the RanoreX-
Path expression using the 'Highlight current' context menu item within Ranorex Repo-
sitory. If the path seems to be correct, try to confirm that the required dialog or appli-
cation is valid at the time of automation, and additionally increase the 'SearchTimeout'
property for the related Application folder.

Lets extend our current recording to see when it is necessary to change the search
timeout value for a repository element. At the position where were currently perform-
ing the last action (clicking the Delete button) in our current recording we add a new
mouse action which performs a click on the Save button.

Ranorex Tutorial 25
Chapter 4 | Ranorex Recorder Capture/Replay Editor

Adding a new mouse action item

To add a new action on the Save button, we need to add the button to the repository
using the integrated Element Browser view. Simple track the Save button by clicking
the tracking button within the Element Browser.

Start tracking session to get the Save button activated within the Element Browser

Now drag&drop the element from the browser tree directly into the repository

and connect it with the newly created action item in the recording.

Ranorex Tutorial 26
Chapter 4 | Ranorex Recorder Capture/Replay Editor

You can now replay only this single action by selecting the context menu item Play
Selected Item/s to check if it works and then continue with the just opened Saving
data dialog. Track the OK button of the message box the same way you have done
it before and then add a new mouse action to the recording which makes use of the
newly added button.

Extended recording with additional click actions on the Save and on the OK buttons

Replay the complete recording to verify the correct execution of the existing items and
of the manually added action items.

Our test application simulates every 1.5 seconds for each added list item to store its
data, which in our case results in a delay of 1.5 seconds before the dialog appears.
Lets have a more detailed look in our repository:

Changing Search Timeout value for the application folder SavingDialog

To see how that value influences the replay of the current recording simply decrease
the timeout value from 5000ms to 1000ms and start the execution (compiled execut-
able) again.

Ranorex Tutorial 27
Chapter 4 | Ranorex Recorder Capture/Replay Editor

Generated report which includes the exception that the Ranorex was not able to find
the dialog

The report shows that Ranorex was not able to find the ButtonOK, because its parent
folder was not found within the specified timeout of 1000 milliseconds. That demon-
strates how the repository information is used. First, Ranorex tries to resolve the Ra-
noreXPath for the parent folder of the item ButtonOK and if found, then tries to
search for the button inside.

Data Driven Recordings


The next example illustrates how to extend our current recording with test data stored
within a simple CSV file.

1. Parameterize the current recording:

Open the user code C# file of the recording and implement the following public
properties:

/// <summary>
/// The Recording1 recording.
/// </summary>
public partial class Recording1
{
// Create a new property 'FirstName'
public static string FirstName
{
get;set;
}

// Create a new property 'LastName'


public static string LastName

Ranorex Tutorial 28
Chapter 4 | Ranorex Recorder Capture/Replay Editor

{
get;set;
}

static Recording1()
{
//Your recording specific initialization code goes here.
}
}

2. Convert the KeySequence actions into user code to use the properties instead
of fixed values:

We have already done one conversion during the user code example before.
Now we convert the first key sequence into a user code action and specify an
appropriate method name:

After we have created both user code methods SetFirstName and SetLast-
Name we switch to the user code file by simply selecting the context menu
item View User Code.

public static void SetLastName()


{
Keyboard.Press(LastName);
}

public static void SetFirstName()


{
Keyboard.Press(FirstName);
}

Now, our recording can be parameterized before the execution is triggered


through the start method.

3. The next step is to connect external test data to our recording.

Now, add the CSV file from the Data folder which is part of Training folder to
your Ranorex Studio project.

Ranorex Tutorial 29
Chapter 4 | Ranorex Recorder Capture/Replay Editor

Select the CSV file and copy it (dont create a link on it) to your project.

The file contains comma separated test data for some VIPs. To get access to these
records we need to add a connector class by adding an existing Item as described
above. The CSVConnector.cs file is located in the Connector directory.

Open the Program.cs file and extend the existing code with the following:

try
{
// Create a new CSVConnector object
CSVConnector csvConnector = new CSVConnector(@"..\..\TestData.csv");

// Read every row from connector and send to AddVIPApplication.


foreach(DataRow row in csvConnector.Rows)
{
Recording1.FirstName = row["FirstName"].ToString();
Recording1.LastName = row["LastName"].ToString();

Recording1.Start();
}
}

Press the play button (recompile project) to start the data driven test example.

Ranorex Tutorial 30
Chapter 5 | Ranorex Studio Part II

5 Ranorex Studio Part II


Ranorex Automation Library
When we look at the code generated by Ranorex Recorder, we see that the whole au-
tomation process is done by some simple mouse clicks, keyboard actions and valida-
tion points. This is exactly what a manual tester can do, because there is nothing more
than a mouse and a keyboard available to interact with the GUI. But, does a test au-
tomation engineer require more? In the case of building complex test automation
frameworks, it is helpful to have an API which allows you to take some shortcuts and
create reusable and robust automation modules.

Using the Ranorex Repository in code

As we can see in Recorder-generated code, all mouse-related actions are based on re-
pository objects. In most cases Ranorex Recorder generates code lines like the follow-
ing:

repo.SavingDialog.ButtonOK.Click();

Each repository item represents a logical Ranorex adapter like Button, Text, ListI-
tem or Menu. The simplest action Click can be performed on every adapter type.
But depending on the type of adapter, the Ranorex API provides many other methods
and properties as the following code example illustrates:

// Setting the value of the text field


// without performing a keyboard action
repo.MyApplicationToTest.InputFields.FirstName.TextValue = "Paul";
// Selects first three characters of the textbox
repo.MyApplicationToTest.InputFields.FirstName.Select(0,3);

The example shows, that instead of always performing mouse actions in combination
with keyboard actions, you can take a shortcut by using the methods and properties
provided by the logical adapter.

Open the Ranorex API documentation which is directly available within Ranorex Stu-
dio using the Help menu to get an overview of the methods and properties provided
for each adapter.

Ranorex Tutorial 31
Chapter 5 | Ranorex Studio Part II

Each item and each folder type of the repository provides an additional object item de-
clared with '<ObjectName>Info'. It is used to access item related attributes without
accessing the GUI element directly. The info object is mainly used to check whether an
item or a folder path is valid.

Working without Ranorex Repository

Its not absolutely necessary to use Ranorex repositories. The Ranorex API provides an
alternative way to work on Ranorex adapters. The simpliest way to create for instance,
a Button adapter for the Add button of our VIP Application, is to drag&drop the ele-
ment from the Element Browser directly into the code editor to get the following:

Button btAdd=
"/form[@controlname='formVipApplication']/button[@controlname='btAdd']";

Ranorex Tutorial 32
Chapter 5 | Ranorex Studio Part II

In that case, Ranorex creates an object of type Ranorex.Button automatically based


on the RanoreXPath expression provided by the Element Browser.

Another way to access GUI elements of an application is to search for them step by
step:

// Search for application 'VIP Database'


Ranorex.Form vipApp = Host.Local.FindChild<Ranorex.Form>("VIP Database");
// Search for button with label 'Clear'
Ranorex.Button clear = vipApp.FindChild<Ranorex.Button>("Clear");
// Press button by calling the method 'Press'
// provided by the Button adapter class
clear.Press();

Within the code, we start to search for a Ranorex.Form object with label VIP Data-
base beginning at the root element which is represented by the Host.Local object.
Please keep in mind that all listed elements within the Ranorex Spy tree can be found
using the Find() methods like described above.

Always consider that GUI elements, applications or dialogs are only accessible, when
they can be discovered by Ranorex Spy too. Thats because Ranorex Spy uses the
same API to build the element tree as your test automation code used to find said
elements. All the information which is required for validation like the value of a text
box is shown in the General tab of Ranorex Spy.

A more detailed look at the Add button of our VIP Application reveals that the ele-
ment provides three different adapter types.

Ranorex.Button
Ranorex.Control
Ranorex.NativeWindow

The Button adapter is used when transferring an item to the repository because the
repository always refers to an item by its intuitive logical adapter name.

The adapters Control and NativeWindow are technology dependent adapters. The
next few lines of code describe how to get access to the properties provided by a tech-
nology adapter.

// Create Button adapter object with RanoreXPath


Ranorex.Button button=
"/form[@controlname='formVipApplication']/button[@controlname='btAdd']";
// 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");

In the example above we convert the object of type Button into a Control adapter,
which allows us to access WinForms specific properties like BackColor. Such technol-
ogy adapters enable us not only to get access to the adapter related properties
which are already shown within the General tab of Ranorex Spy but also to use
special methods to retrieve extended information from a GUI element under test.

Ranorex Tutorial 33
Chapter 5 | Ranorex Studio Part II

Failure Handling, Exceptions and Report generation


Due to the use of modern programming techniques within the .NET environment, the
Ranorex API supports to handle failures as exceptions. As you can see in every Pro-
gram.cs file which is automatically part of every newly created Ranorex command
line project type the template includes a try-catch block:

try
{
// Create a new CSVConnector object
CSVConnector csvConnector = new CSVConnector(@"..\..\TestData.csv");

// Read every row from connector and send to AddVIPApplication.


foreach(DataRow row in csvConnector.Rows)
{
Recording1.FirstName = row["FirstName"].ToString();
Recording1.LastName = row["LastName"].ToString();

Recording1.Start();
}
}
catch (RanorexException e)
{
Report.Error(e.ToString());
Report.Screenshot();
error = -1;
}

Also, our example executes all the Ranorex related automation tasks within the try
block. If there goes something wrong during automation, like a dialog that cant be
found within the specified timeout, a RanorexException is thrown which is caught by
the catch block. In the above code example we handle all Ranorex exceptions and add
the additional exception data to the report log file.

The Ranorex Report class is used to generate test execution reports during test
automation. Each Ranorex based test should log at least two messages showing the
start and end time of the test. The more information is logged during automation, the
easier it is to find out what went wrong - as long as the generated report can be
filtered.

The Ranorex Report class provides several methods to distinguish between important
test or validation logs and simple test development debug information.

During test development, it is often necessary to log messages containing more devel-
oper-specific information; therefore the Report class provides four different methods
and log levels for test developers.

// Setup Reporter
Report.Setup(ReportLevel.Debug, "myReport.rxlog", true);

// Log four different levels


Report.Debug("Debug message");
Report.Info("Info message");
Report.Warn("Warning message");
Report.Error("Error message");

// Stop Report - log file will be finished

Ranorex Tutorial 34
Chapter 5 | Ranorex Studio Part II

Report.End();

Generated Report

From the perspective of a test manager, it's more important to know whether a test
failed or not. Use the following methods to log information related to logical test case
success or failure. Additionally, the Validate class automatically reports successful or
unsuccessful validations using these methods:

// Setup Reporter
Report.Setup(ReportLevel.Debug, "myReport.rxlog", true);

// Log test specific information


Report.Failure("Test case failed");
Report.Success("Test case successfully finished");
Ranorex.Validate.AreEqual("compareText", "compareText","String comparison",
true);

// Log current system environment


Report.SystemSummary();
Report.End();

Generated report

How to handle unexpected dialogs


The Ranorex API provides different ways to distinguish whether an application or di-
alog is active and ready for user input. Each dialog and application represented
through the Ranorex Form adapter has an Active property to determine whether the
application window is in the foreground or not. Also, a top level form or message box
can be found by combining the RanoreXPath with the Active property:

public static void CheckActiveWindow()


{
// Check if the application is active before

Ranorex Tutorial 35
Chapter 5 | Ranorex Studio Part II

// performing a mouse click actions on it


if (repo.MyApplicationToTest.Self.Active == false)
throw new RanorexException("Application is not active");
// Clik the 'Save' button
repo.MyApplicationToTest.ButtonSave.Click();
// Use RanoreXPath to find the active top level window
Ranorex.Form activeForm = "/form[@active='True']";
// Send a screenshot of the top level form to the report
Report.Screenshot(activeForm);
}

Usually, Ranorex tries to ensure visibility of an element before performing an action.


But in the case of modal dialogs or message boxes, Ranorex cannot force a window in-
to the foreground.

How to organize a test automation project with Ranorex Studio


There are many different possibilities for organizing a Ranorex Studio test automation
project. But, the main goal when doing professional test automation with Ranorex is to
create reusable automation modules. This can be realized by distinguishing between
commonly used automation modules, which perform actions like starting an applica-
tion, and specialized test modules performing a narrowly defined task. Lets have a
look at the example project which is part of the Training folder and called TestProject
to see how a small test project created with Ranorex Studio could look like:

Multiple test cases managed within one project

The example project contains different folders to manage test cases, test data, and
utility methods separately. In addition, the project contains only one main repository
file which is used by every recording and every automation module.

Ranorex Tutorial 36
Chapter 5 | Ranorex Studio Part II

Running compiled executable


By selecting the Build menu item Ranorex Studio compiles the test code and gene-
rates an executable file which is placed within the projects bin\debug folder as a de-
fault. The TestProject example implements evaluation of arguments to support com-
mand line options. In addition, the project contains a simple batch file describing how
to trigger each test separately.

Batch file executeTests.bat using one command line option to specify the test case to
execute

To start the batch test, simply select the context menu item Open Containing Folder in
Explorer and double click the file within the file explorer.

Ranorex Tutorial 37

Вам также может понравиться