Ranorex Documentation Download

Copy and paste this link to your website, so they can see this document directly without any plugins.



Keywords

Ranorex, Figure, test, Contents, your, with, from, repository, will, item, action, recording, code, using, application, used, that, which, file, device, within, module, have, Note:, this, button, following, Test, report, element

Transcript

Test Automation Guide
Ranorex
Test Automation Guide
Based on version 7.0
© Copyright 2017
Ranorex GmbH
Created on: March 29, 2017
Ranorex Version: 7.0
Authors:
Roland Enzinger, Martin Fahrenberger,
Christoph Preschern, Christina Reisinger and Tobias Walter
Special Thanks to:
Michael Gissing, Alexander Hoisl
Contents
Ranorex Studio - The Layout 1
Studio Start Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Working environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
#1 - Projects View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
#2 - Module Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
#3 - File View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Lesson 1: Getting Started 12
Preparing to Record User Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
System Under Test: KeePass Password Safe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Recording a Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Analyzing Recorded Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Executing the Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Lesson 2: Ranorex Modules - Test Actions 29
Lesson 3: Data-Driven Testing 32
Using Variables within Recordings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Using Variables within the Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Creating Test Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Combining Variables with Test Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Combining Variables with Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Invoking Actions: Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Executing Data Driven Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Lesson 4: Ranorex Test Suite 47
Test Suite Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Module Group Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
General structure of a test suite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Running a Test Suite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Running Tests without Ranorex Studio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Test Suite Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Test Case and Smart Folder Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Using Data in Test Suites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Lesson 5: Ranorex Recorder 80
Before Starting to Record . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
During Recording . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
After Recording . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Replay and Debug Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Recorder Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
User Code Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Additional Editing Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Image-Based Automation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Lesson 6: UI Mapping with Ranorex Repository 138
Adapting an Existing Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Adding Repository Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Waiting for UI Elements - Repository Timeouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
Editing RanoreXPath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Repository Separation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Repository Settings Dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Repository Item Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Lesson 7: Code Modules 166
Creating Code Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
I
Using Repository within Code Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Accessing Screen Shots within Code Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
Using Variables with Code Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Using Code Modules within Test Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
Lesson 8: Reporting 177
JUnit-compatible reports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Progressive report preview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
Reading Ranorex Reports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Report Levels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Logging Individual Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Updating the Custom Report Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
Create a Custom Report Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
Lesson 9: Ranorex Spy 196
Short Introduction to the Structure of RanoreXPath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
Capture Screenshot Files for Image-Based Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
Tracking UI Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
RanoreXPath Edit Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
The Path Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Creating Ranorex Snapshot Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
Ranorex Settings 235
Settings in Ranorex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
User settings and solution settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Where to access settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
User settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Solution settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
Settings overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
Improved WPF plug-in . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
Ranorex Remote 256
Ranorex Remote at a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
What to find where? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
Ranorex Agent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Install and set up Ranorex Agent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
Configure Ranorex Agent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
Remote Pad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
Adding Ranorex Agents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
Agent List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
Execute tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
Run History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
Remote System Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
Remote Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
Remote FAQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
User Code Library 301
Collections and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Using the User Code Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Endpoints 309
Shortcuts and command line execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Endpoint list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Adding Android endpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
Adding iOS endpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
Adding WebDriver endpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
Selenium WebDriver integration 329
II
Setting up a Selenium WebDriver infrastructure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
Running Selenium Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
Web test guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
Code Examples 331
Using Repository in Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
Wait for UI Elements Using Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
Create Adapters to Access More Properties and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
Create a List of Adapters From a Repository Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
Using Validate Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
Forcing a Test Case to Fail Using the Validate Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
Forcing a Test Case to Fail using Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
Set Up Automation Speed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
Accessing Test Case & Test Suite Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
Advanced Code Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
How to do image based automation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
How to find and compare images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
Handling unexpected Dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
Advanced Validation - Clipboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
Advanced Validation - Whole Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
Advanced Validation - Whole Table in Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
Advanced Validation - File (text-based) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
Advanced Validation - File (non text-based, binary) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
Advanced Validation - Database (Single Field) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
Advanced Validation - Database (Whole Table) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
Advanced Validation - XML code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
Data Connectors 360
Manage Data Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
Kind of Data Connectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
Simple Data Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
CSV File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
SQL Connector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
Excel File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
Instrumentation Wizard 372
Running Instrumentation Wizard from the Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . 374
Java AWT/Swing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
Adobe Flash/Flex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
Mozilla Firefox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
Google Chrome . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
Apple Safari . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
Android . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
iOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
Technology Instrumentation 402
Flash/Flex Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
Testing of Java Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
Qt Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
Testing of Legacy Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
Testing of SAP Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
Testing of CEF applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
General Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
RanoreXPath 428
RanoreXPath Syntax Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
Result Set Selector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
Advanced RanoreXPath Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
III
RanoreXPath with Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
RanoreXPath Weight Rule Library 435
Why RanoreXPath Weight Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
How to Add Your Own RanoreXPath Weight Rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
How to Add Shared RanoreXPath Weight Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
Rule Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
Ranorex UI Adapter 440
Multiple Adapters for one GUI element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
Mobile Testing 446
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
Versioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
Mobile Download Archive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
Android Testing 448
Infrastructure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
Record and Run an Android Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
Manage Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
Non-UI Testing on Android . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
Automation of System Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
Run Your Test on Any Android Device . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
Testing of Mobile Websites on Android . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
Instrumentation with Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
Add Device with Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
Testing of Android Wear Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
iOS Testing 502
Infrastructure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
Record and Run an iOS Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
Instrumentation and Preparation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
Non-UI Testing on iOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
iOS Service App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
Run a Test on Any iOS Device . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
Testing of Mobile Websites on iOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
Instrumentation with Source Code on iOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
Web Testing 544
Architecture of Websites in the Ranorex Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
Find or filter Web Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
Cross-Browser Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
Recordings & Repositories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
Samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
Source Control 553
Introduction to Source Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
Important notice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
Source Control in Ranorex Studio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
Git . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
Subversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
Team Foundation Version Control (TFVC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
Integration 595
IV
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
Continuous Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
Test Management and Application Lifecycle tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
Source Control / Revision Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
Ranorex Studio IDE 597
Create . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598
Build . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
Run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603
Adding New Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604
Solution Explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607
Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 610
Code Completion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 616
Code Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
Code Navigation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619
Refactoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620
Visual Studio Integration 621
Create a new Visual Studio project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621
Add Ranorex core assemblies as references . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621
Write some Ranorex automation code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
System Requirements 624
Supported Operating Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
Software Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
Hardware Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
Required Disk Space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
Ranorex License Manager Firewall Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
Ranorex Agent Firewall Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626
System Requirements for Ranorex Versions up to 6.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626
64-bit Platforms 628
Remotely Working with Ranorex 629
Do not Automate via Remote Desktop Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
Do not Close or Minimize the RDP Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
Disable Mouse/Keyboard Activities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
Use same Color and Resolution Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
Increase Timeouts on Virtual Machines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
Keeping remote session unlocked even if closing it . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
Silent Installation of Ranorex 631
Installation Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631
Installation Command Line Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631
Install Ranorex License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632
XCOPY Deployment 633
Running tests without Ranorex Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633
Deploy Ranorex Libraries and Assemblies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633
Deploy Ranorex License Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633
Deploy Your Ranorex Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633
Licensing 636
License Registration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 636
Installing a Node Locked License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 636
Installing a Floating License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638
Uninstall License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 640
V
Transfer Licenses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642
How to instructions 643
How to add a solution settings file to a solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
How to create a Ranorex Snapshot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
How to create a compressed Ranorex solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650
How to create a compressed Ranorex Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 651
FAQ 653
How does Ranorex identify UI elements? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 653
Is it possible to run the same Ranorex test code on Vista and XP? . . . . . . . . . . . . . . . . . . . . . . 653
Is it required to use RanoreXPath for test automation? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 653
Does Ranorex support data driven testing? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 654
How can I speed up my Excel-based data connector? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 654
What to do when items can’t be found during Ranorex test execution? . . . . . . . . . . . . . . . . . . . . 654
Is it possible to extend recordings with user specified code actions? . . . . . . . . . . . . . . . . . . . . . . 654
What is the difference between Adapter and Element? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 654
Is it possible to trigger Ranorex tests from an existing test or build environment? . . . . . . . . . . . . . . 655
Can I run my tests on machines where I am not allowed to install Ranorex? . . . . . . . . . . . . . . . . . 655
Can I use Ranorex libraries within Visual Studio? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655
What shall I do with unexpected dialogs and popup windows during test automation? . . . . . . . . . . . . 655
Is it possible to test Silverlight applications with Ranorex? . . . . . . . . . . . . . . . . . . . . . . . . . . 655
Is it possible to automate a webpage without moving the mouse pointer? . . . . . . . . . . . . . . . . . . 655
What are the system requirements for developing and running Ranorex tests? . . . . . . . . . . . . . . . . 655
Are there known incompatibilities with other software? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656
VI
Contents
Ranorex Studio - The Layout
This initial lesson will introduce the main components of the Ranorex Studio environment.
Studio Start Page
When Ranorex Studio opens up, the start page provides the following possibilities:
ˆ Accessing recently opened projects
ˆ Directly creating new test solutions
ˆ Accessing product samples (see below)
ˆ Directly opening existing solutions
ˆ Getting detailed information about the installed license
ˆ Downloading the latest version of Ranorex
ˆ Viewing the latest announcements
Figure 1: Ranorex Studio startpage
Product samples - desktop, web, mobile and cross-platform
In Ranorex Studio, several product samples are available on the startpage. Studying them more closely you can learn
how to create automated tests for desktop, web, and mobile applications. Additionally a cross-platform sample is
available performing tests on all mentioned platforms in one test scenario.
1
Contents
Access these samples directly on the start page in section ”Sample projects” (see screenshot below).
Figure 2: Access Ranorex Product Samples
Figure 3
Sample on Desktop
This sample performs automated tests in the desktop application KeePass.
Learn something about: #variable binding #data connectors #usercode actions #arguments #optional actions
#nested test cases #module groups #global setup/teardown regions
2
Contents
Figure 4
Sample in web
This sample performs automated tests in the online blog tool WordPress.
Learn something about: #module library #popup watcher #project organization #report screenshot #validation
#web testing #handling flyout menu #setup/teardown regions #data binding
Figure 5
3
Contents
Figure 6
Sample for mobile apps on Android and iOS
This samples for Android and iOS perform automated tests in the mobile app KeePass.
Learn something about: #mobile testing #android #ios #deploy mobile app #module groups #usercode actions
#setup/teardown regions #data connectors #arguments
Figure 7
Cross-platform sample
This sample performs automated tests in desktop, web, and mobile applications.
Learn something about: #cross-platform test #end2end test #ios #android #deploy mobile app #module library
#project organization #popup watcher #web testing #mobile web testing #setup/teardown regions #data binding
Working environment
Before you start creating your first test case with Ranorex Studio you should know about the main views and layout
of Ranorex Studio.
4
Contents
Figure 8: Ranorex Studio main views
Screencast: You can find an introductory screencast (Quick Start with Ranorex Test Automation) here:
http://youtu.be/0S YC7uwI-s. At the very beginning of the video you’ll learn the different views offered by
Ranorex Studio.
#1 - Projects View
A Ranorex Studio project is based on files and uses the same project file format as Microsoft Visual Studio 2008/2010.
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 project’s test suite (*.rxtst)
Module Group Represents the project’s module groups (*.rxtmg)
Repository Used to manage UI elements (*.rxrep)
Recording Represents an automation module based on capture/replay (*.rxrec)
Code 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 Lesson 5: Ranorex Recorder, Lesson 6: UI Mapping with
Ranorex Repository, Module Groups, or Lesson 7: Code Modules.
#2 - Module Browser
The ’Module Browser’ view lists all available modules (Lesson 7: Code Modules & Lesson 5: Ranorex Recorder) 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.
5
Contents
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
opened in the Studio’s file view. This view is mainly used for the actions shown below.
Figure 9: Creating or adapting a recording module
6
Contents
Figure 10: Working with the repository
7
Contents
Figure 11: Working with the project’s module groups
8
Contents
Figure 12: Writing code modules
9
Contents
Figure 13: Viewing a test report
10
Contents
Figure 14: Working with the project’s test suite
11
Contents
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
Screencast: The screencast ”Quick Start with Ranorex Test Automation” gives a short introduction
to the Ranorex Recorder. You can jump directly to the noted position in the video by clicking http:
//youtu.be/0S YC7uwI-s#t=1m8s.
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 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/.
12
Contents
Figure 15: 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 Case.
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. Click the ’New Test Solution. . . ’
button to create a blank test suite project.
13
Contents
Figure 16: Ranorex Studio Start Page - creating a new test solution
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.
Note: Because of possible performance and security impacts, projects should not reside on a network drive
(neither should Ranorex itself be installed on a network drive). It’s recommended to use a version control
system (VCS) instead.
Click the ’Create’ button and a new test suite project opens.
14
Contents
Figure 17: Specify programming language and project name
Figure 18: 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.
15
Contents
Figure 19: 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 (\Samples\Desktop\KeePass Sample\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
16
Contents
Figure 20: Open project folder in explorer to copy the sample application to the project folder
17
Contents
Click the ’Record’ button in order to start. The Recorder assists you in preparing the application under test. Choose
’Desktop’ as technology and click on ’Add app’ to add KeePass to the list of applications under test.
Figure 21: Choosea technology to record your test
Figure 22: Ranorex automatically starts the specified application
Click on ’Record’ in order to record the test. The KeePass application opens and the Ranorex Recorder starts running.
18
Contents
Figure 23: Recording actions for the KeePass application
Note: You will notice that a red border will be shown when moving the mouse over a UI element indicating
which element is taken for automation. The red border will assist you during the recording process. You can
en-/disable this feature in the Recorder Settings Dialog.
Enter the default Password.
ˆ Click on the text field next to the ’Master Password’ check box
ˆ Type in the default password (’rx’)
Figure 24: KeePass Login Dialog
19
Contents
Figure 25: KeePass application
Open the ’Add new Entry’ Form.
ˆ Click on ’Edit’ in the main tool bar
ˆ Click on the ’Add Entry’ menu item
Figure 26: KeePass application with sub menu ’Edit’ (Menu item ’Add Entry’ is selected)
Add a new entry to the KeePass application.
ˆ Click on the ’Title’ text box and type in ’WordPressDemo’
ˆ Click on the icon button (with the key symbol)
– Choose any icon (e.g. the second one)
– Click on ’Close’
ˆ Click on the ’User name’ text box and type in ’admin’
ˆ Click on the ’Password’ text box
20
Contents
ˆ Click again with the right mouse button
ˆ Choose ’Select All’
ˆ Type in ’demo123’
ˆ Repeat the same for ’Repeat’ text box
ˆ Click on the ’URL’ text box and type in http://bitly.com/wp demo
ˆ Click the ’Expires’ button on the right (watch symbol)
– Choose ’1 Year’ menu item
ˆ Click on ’OK’ button
Figure 27: KeePass form for adding a password entry
21
Contents
Figure 28: KeePass form for choosing an icon
Figure 29: KeePass expiration sub menu
22
Contents
Validate the result.
After adding a new password entry, a new row is added to the KeePass grid holding the recently entered item. Click
the ’Validate’ button within the ’Recording’ toolbar to check whether the entry appears in the grid. Move the mouse
pointer to the grid (i.e. the first cell) and wait a moment until the underlying UI element is highlighted.
Figure 30: KeePass form with highlighting frame for validation
At the first step of the validation you can choose the UI element you want to validate. Verify that the correct element
is selected and click on the ’Next’ button. At the second step, all available attributes for the given UI element to
check are shown. Just click the ’OK’ button in order to accept the preselected ’Text’ attribute.
Figure 31: Choose UI element to validate
23
Contents
Figure 32: Choose attribute to validate
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.
Figure 33: Screenshot indicating the save button in the tool bar
Stop the recording by pressing the ’Stop’ button in the recorder tool bar.
24
Contents
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 recording.
Figure 34: 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
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.
25
Contents
Figure 35: 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.
Figure 36: Test run succeeded
26
Contents
Figure 37: Test run failed
In order to force an error as shown in the picture above, simply modify the expected value used in the validation step
of the recording (e.g. ’Typo3Demo’ instead of ’WordPressDemo’).
Figure 38: 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. In short, it is best to copy the complete output folder (e.g. ’bin/debug’) to the
target machine.
Figure 39: ’MyFirstTestProject.exe’ located within the build folder of the project
27
Contents
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.
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.
28
Contents
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. In the following
section you will learn how to separate existing recordings into smaller pieces to be reused by other test cases.
Screencast: The screencast ”Ranorex Modules Test Automation Actions” provides a short introduction to
preparing recorded actions for reusability by extracting reusable Ranorex Modules. This screencast can be
found at http://youtu.be/GrrKnf8cQ2g
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
– Chose an icon
– Set the expiration value
ˆ Validated the existence of the newly created entry in the grid
ˆ Deleted the entry
ˆ Saved the changes
ˆ Closed the application
In order to split recordings into smaller automation modules, select related actions and use the context menu item
’Move to new Recording Module’. Within the underlying recording, the three actions performing 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.
29
Contents
Figure 40: Move login actions to a new recording
Figure 41: Create a new recording named ’LogIn’
Then, select and move all items used to add a new entry to the database to a new recording named ’AddEntry.rxrec’.
Repeat the previous steps to create modules for ’ValidateEntry’, ’DeleteEntry’, ’SaveDB’ and for ’CloseSUT’.
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 separate 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.
Figure 42: Use the drag and drop feature to specify your test case within the test suite view
When having a huge amount of different modules you can use the search functionality of the Ranorex Module Browser
which searches through the module name as well as the modules XmlDoc Summary. The XmlDoc Summary can be
set in the properties of the module. You can open the properties by right-clicking a module in the Ranorex Module
Browser and choosing ’Properties’ in the context menu.
30
Contents
Note: When you are going to use the XmlDoc Summary, be sure to enable XML documentation creation
in your project settings. In Ranorex Studio this setting can be found in the ’Compiling’ tab in the project
properties.
Figure 43: Set a modules XmlDoc Summary
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.
31
Contents
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,
CSV 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.
Screencast: There is a screencast called ”Data Driven Test Automation with Ranorex” which might be
useful as you get a quick overview of how to get started with using external data sources to drive Ranorex
test cases: http://youtu.be/TRQy2Jl79-U
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
ˆ Creating Test Data
ˆ Combining Variables with Test Data
ˆ Combining Variables with Parameters
ˆ Invoking Actions: Selection
ˆ Executing Data Driven Tests
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 ’AddEntry’ 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.
32
Contents
Figure 44: Create a new variable for a key sequence action item
Figure 45: Create a new variable
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 ’AddEntry’ 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’ value (1 week, 1 year. . . )
- you need to define a variable used for identification within a RanoreXPath expression.
Select that action item within the ’AddEntry’ recording which simulates a click on a menu item and open the context
menu as shown below. Click on ’Make Item Variable. . . ’ to open The Path Editor.
33
Contents
Figure 46: ’Make Item Variable’ menu item from context menu in Recorder
Typically the menu item for the ’Expires Date’ in the 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.
Figure 47: Create a new variable for the expires menu item
When looking at the repository, you can see that the item pointing to the menu item is now using the variable within
the path expression specified previously.
34
Contents
Figure 48: Variable repository item
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 ’AddEntry’ 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 of all variables used within the recording simply
click the ’Variables’ button as shown below.
Figure 49: Open the recording’s variable dialog
35
Contents
Figure 50: 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 ’AddEntry’ recording and open the ’Data Source’ dialog by clicking the ’Manage
Data Sources’ button in the tool bar.
Figure 51: Open the ’Manage data sources . . . ’ dialog
Assuming someone is keeping his/her 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.
Note: The top row is handled as a header. Therefore the cells of the first row will be interpreted as captions
for the current column.
36
Contents
Figure 52: Use an Excel file for data-driven testing
Now create a new data connector by clicking on ’Use Excel file. . . ’.
Figure 53: Create a new Excel connector
37
Contents
Figure 54: Specify the filename from the Excel file
For further information about different Ranorex data connector types have a look at Data Connectors.
Note: To protect proprietary data like passwords you can mask specific columns of your data source.
Note: It is recommended to store your Excel data files in the native binary format xlsb instead of the
suggested default format xlsx. The binary format is up to ten times faster than xlsx, and supported since
Microsoft Office 2007.
Combining Variables with Test Data
In order to combine your Excel file with the current test case - and finally with the ’AddEntry’ recording which is used
by the test case - you need to open the data binding dialog using the context menu as shown below.
38
Contents
Figure 55: Open data binding dialog
Note: Please assure that the ’ExcelConnector’ is chosen in the ’Data Source’ tab sheet (drop down in the
middle of the 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 ’AddEntry’ module.
Figure 56: Connect data columns with module variables
Note: Variable binding (e.g. to a data column) only takes place if the test automation is run from the test
suite view. When running modules separately (e.g. ”Play” in recorder), variable’s default values are used.
39
Contents
Combining Variables with Parameters
Parameters can be useful when automated tests are executed under different environment-related conditions. An
automated test on Windows 7, for example, may need different path values in comparison to a test execution on
Windows XP. 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 can help with environment-related attribute values and similar issues 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’.
Figure 57: 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.
Figure 58: Open global parameters dialog
40
Contents
Figure 59: 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’. Click ’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.
41
Contents
Figure 60: Bind global parameter to the variable used within recording ’StartSystemUnderTest’
Note: By pressing the button ’Auto-Create’ a parameter for each unbound module variable will be generated
based on the name of the module variable. By pressing the button ’Auto-Bind’ unbound module variables will
be bound to parameters having identical names.
Note: When moving the mouse over a module in the test suite a tool tip will appear displaying which variables
are bound and which are not
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 ’AddEntry’ recording. The values for the title, username, password, URL and expiration
will not cause any problems during automation. Considering 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.
Note: Variable binding (e.g. to a global parameter) only takes place if the test automation is run from the
test suite view. When running modules separately (e.g. ”Play” in recorder), variable’s default values are used.
Invoking Actions: Selection
KeePass offers a list of icons which can be accessed via the button next to the label ’Icon’:
42
Contents
Figure 61: Button to open the Icon Picker
Figure 62: Form for choosing an icon for a password entry
43
Contents
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 click action (#5) and click the ’Add New Action’ button as shown below.
Figure 63: 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 ’IconItem’.
Figure 64: 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 ’ListItem’ shows a ’Select’ method which you can chose as seen in following figure.
44
Contents
Figure 65: 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 Tests
Before executing the test suite, it’s necessary to modify the recording ’ValidateEntry’ in order to be independent from
the constant values used during recording. Therefore the constant value ’WordPressDemo’ should be replaced by
variables. First, please replace the match-value in the validation action.
Figure 66: Replace match value by a new variable
Finally, please modify the text-attribute-value in the RanoreXPath expression of the assigned repository item as
learned in the previous sections.
Figure 67: Replace value by variable in RanoreXPath
45
Contents
Note: Don’t forget to bind the variables to the excel-column.
Now switch back to the test suite view and start your data driven test by clicking the ’Run’ button.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.
Figure 68: Report file showing two iterations of the test case
46
Contents
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
ˆ Running a Test Suite
ˆ Running Tests without Ranorex Studio
ˆ Test Suite Settings
ˆ Test Case and Smart Folder Settings
ˆ Using Data in Test Suites
Test Suite Editor
After the creation of a new test suite project, a Ranorex Studio project automatically contains a .rxtst
file.
By default the test suite file is opened automatically.
47
Contents
Figure 69: Ranorex Test Suite file
Using 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.
Figure 70: Ranorex Studio tool bar
Adding a new test case or smart folder
You can add a new test case or smart folder by clicking the ’ADD’ 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
ˆ Smart folders
ˆ Recording modules
48
Contents
ˆ Code modules
ˆ Module groups
These items can be added and arranged according to a special hierarchy. You can find out more about it General
structure of a test suite.
Figure 71: Add a new test case
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’.
Figure 72: 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.
49
Contents
Figure 73: Add an existing recording module
Figure 74: Select ’StartSUT’ module from the list
50
Contents
Press ’OK’ to add the record module to the test case.
Repeat the steps to add the record items ’LogIn’ and ’CloseSUT’ to the test case.
Insert a New Recording Module
For now the test case only covers starting the application under test, logging in and closing 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.
Figure 75: Insert a new recording 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 ’Instant Recording’ option because the system under test will be started by
the reused recording module ’StartSUT’.
Figure 76: Newly created recording scenario
51
Contents
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). Since the content of the cell
(KeePass’ version number) is used for identification, a higher version number would cause the test case to fail because
the cell can’t be found anymore - independent from the match of version number in the validation step itself. To
avoid this, the path to this cell should be modified to be more robust. The path can be edited using The Path Editor.
Additionally it should not use the version number itself for identification.
Figure 77: Click the ’Edit in Spy’ button open the path editor
Figure 78: Change attributes for identification: deselect text attribute and select column- and row-index attributes
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 ’varCurrentKeePassVersion’ with a
default value ’2.20.1’ instead of matching against the constant value. This module variable could be bound to a new
global variable ’GlobalCurrentKeePassVersion’.
Now the test case ’ValidateVersionNumber’ is ready to be executed.
Use the context menu item ’Run Selected Test Case’ to run it and see whether it works or not.
52
Contents
Figure 79: Run selected test case
Module Group Editor
It can be useful to combine modules which belong together into groups to reuse them more easily.
For example combining the modules ’StartSUT’ and ’LogIn’ into a module group ’StartAndLogin’ within the KeePass
sample project could be useful, because these two modules are needed to start the system under test. The same
applies to the modules ’Save’ and ’CloseSUT’ which can be combined with the module group ’SaveAndClose’.
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 .rxtmg.
Double-clicking this file in the project view will open it in the module group editor.
53
Contents
Figure 80: Open module group editor
After creating a new solution an empty module groups file is created.
54
Contents
Figure 81: 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/smart folder
ˆ Use the context menu in the test suite editor to group selected modules into a module group
Figure 82: Adding a module group to a test case using the context menu in the test suite editor
55
Contents
Figure 83: 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 with the selected modules. In
addition, a possible data binding of selected modules will automatically be applied to the created module group which
therefore is the recommended approach. 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.
Figure 84: Adding an existing module to a module group using the context menu
Next to adding existing modules it is possible to add folders to module groups to add additional hierarchical levels.
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.
56
Contents
Figure 85: Drag and drop module into a module group
To allow for a data driven approach as described in Lesson 3: Data-Driven Testing, it is necessary to pass values from
data sources or parameters through the module group to the modules contained in that module group.
You can define data binding for modules in the module group by using the context menu item ’Data Binding. . . ’
which appears by right-clicking a module group.
Figure 86: 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.
57
Contents
Figure 87: Define which module variables should get their values passed from outside the module group and which
module variables should have constant value
Note: By pressing the button ’Auto-Create’ a group variable for each unbound module variable will be
generated based on the name of the module variable. By pressing the button ’Auto-Bind’ unbound module
variables will be bound to group variables having identical names.
After defining a module group and its data binding, it can be added to a test case or smart folder 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.
58
Contents
Figure 88: Adding a module group to a test case
General structure of a test suite
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.
Figure 89: 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
combinations.
59
Contents
Figure 90: Ranorex test suite structure
#1 Test suite Represents the entire test suite and is the root level of the structure
#2 Test case Represents a test case
#3 Setup region Groups modules used to prepare a test case (e.g. start system under test, initialize a
database, etc.)
#4 Smart folder Used to organize other items. Smart folders can be nested (a smart folder may contain
other smart folders)
#5 Module group Used to group several modules into a reusable set
#6 Teardown region Groups modules used to clean up a test case (e.g. deleting files generated during test
execution, closing application, etc.)
#7 Code module Automation module written in code
#8 Recording module Automation module generated by recording
60
Contents
These items follow a hierarchy. This means that there are rules that define which items may be added directly to
other items in the test suite structure. The table below illustrates this.
You may add:Test casesSmart foldersSetup/teardown regionsModules and module groupsTest suite levelTest caseSmart
folder***Setup/teardown region
Test suite: At the root level, you may add test cases, smart folders, and setup/teardown regions.
Test cases: You may add smart folders, setup/teardown regions, modules and module groups.
Smart folders: You may add test cases*, other smart folders, setup/teardown regions, modules** and module
groups**.
Setup/teardown: You may add modules and module groups.
*Only if the smart folder is not part of a test case. **Only if the smart folder is part of a test case.
Note: If a drag/drop or copy/paste operation would create a nested test case, the affected test case will be
converted into a smart folder instead. The resulting smart folder will work the same way as the original test
case.
Setup and teardown regions
The setup and teardown regions are used to prepare and clean up a single test case run.
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 case for using 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 case for using 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 suite, test case, or smart folder.
Use the context menu to specify which modules or module groups from a test case should be part of the setup or
teardown process.
61
Contents
Figure 91: Add module to setup region
Note: If you want to define one setup and one teardown region for a set of test cases, simply use a smart
folder as shown in the following picture
Figure 92: Smart folder containing test cases for a general setup and teardown region
Note: In order to define global setup and teardown regions click on ’Add Setup’ or ’Add Teardown’ in
context menu of the test suite node and drag and drop the wanted modules or module groups to displayed
the setup and teardown regions.
62
Contents
Figure 93: Show setup and teardown region for test suite node
Figure 94: Drag and drop modules to global setup region
In order to quickly deactivate a certain module, instead of deleting it, use the context menu item ’Disable’.
Searching for elements
Use the ’Search’ text box to find elements in the test suite.
63
Contents
Figure 95: 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 or the run button in the Ranorex
Studio toolbar. This will always run the test suite using the currently selected run configuration.
Run configurations
Run configurations define which test cases and smart folders will be executed during a test. Use the check boxes to
specify which elements you want to be run. Ticking the checkbox at the test suite level will tick all others. You can
also save your current configuration. Here’s how:
ˆ Check the boxes of the desired elements.
ˆ Click the drop-down menu in the test suite editor’s toolbar and select ”Manage Run Configurations. . . ”.
ˆ Click ”Add”.
ˆ Enter a name and click OK.
ˆ You can now apply the run configuration by selecting it from the drop-down menu.
Note: Run configurations can only be used with the test suite they were created in.
64
Contents
Figure 96: Activate different test suite run configurations
Figure 97: Add or remove test suite run configurations
Run iterations
Run iterations let you run specific test cases or smart folders any amount of times during a test run. You can enable
them as follows:
ˆ Click on the test cases(s) or smart folder(s) you want to iterate.
ˆ Go to ”View” and click on ”Properties” or press F4. The properties pad will appear.
ˆ Enter your desired number of iterations in ”Iteration Count”.
The selected items will now be run the specified amount of times during test execution.
65
Contents
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. 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. In short, to
deploy a Ranorex test to a runtime machine it’s required to copy the complete output folder (e.g. ’bin/debug’) to the
target machine.
You can execute the test suite outside Ranorex Studio using one of the following:
ˆ Ranorex Test Suite Runner
ˆ Command Line
Ranorex Test Suite Runner
Simply double-click the *.RXTST file from the project’s output folder to open the Ranorex Test Suite Runner.
Figure 98: External Ranorex Test Suite Runner
You can use the Ranorex Test Suite Runner to run the test suite, execute certain test cases and smart folders or just
run a specific automation module.
Additionally one can create new run configurations the same way as is done within a Ranorex Studio Project.
Running Tests via Command Line
Note: When executing a test suite from command line the return value ’0’ signals the successful execution of
the test script and the return value ’-1’ signals a failure.
Using the following command pattern, you can execute the test suite from the command line:
.exe /
66
Contents
Allowed arguments:
help|? Prints this help text.
listconfigparams|lcp Lists all settable configuration parameters and their values.
config|cfg:= Set values for configuration parameters.
endpoint|ep: Display name of the endpoint to be used as the automation root during test
execution. If no endpoint is specified ’localhost’ is used.
reportfile|rf: 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 Compresses the report (including associated files) to a single archive (”.rxzlog” extension).
JUnit|jr Creates the report in JUnit format as well. The report will be placed in the same location as the original
Ranorex Report.
zipreportfile|zrf: When used with /zipreport|zr, sets the name (and path) of the compressed
report 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| 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.
listtestcaseparams|ltcpa: Lists all test case or smart folder
parameters and their values.
testcase|tc: Runs this test case or smart folder only.
testsuite|ts: Runs the test cases or smart folders defined by the test suite (rxtst) file.
By default
ˆ the rxtst file with the same name as the is used
ˆ or the first rxtst file in the same folder as .
runconfig|rc: Runs the test cases or smart folder of the specified configuration defined
by the rxtst file. Configurations can be edited using Ranorex Studio or TestSuiteRunner. By default, the currently
selected run config is used.
67
Contents
module|mo: Runs the module with the specified name or guid. Assemblies loaded by
and assemblies referenced in the rxtst file are searched.
param|pa:= Creates or overrides values for global parameters specified in
the test suite.
testcaseparam|tcpa::= Creates
or overrides values for test case or smart folder parameters specified in the test suite.
runlabel|rul: Sets a custom runlabel for the test run.
testcasedatarange|tcdr:= Sets the data range
for a test case or smart folder.
Note: Compressed report files (*.rxzlog) can be extracted by right-clicking them in explorer and choosing
’Extract’ from context menu. Report files (*.rxlog) can be compressed by right-clicking them in explorer and
choosing ’Compress’ from context menu.
Some Examples for using Command Line Arguments
Using the KeePass sample test suite - included in Ranorex installation - as reference, the following samples will fulfill
the following use cases:
Start the test suite with setting a global parameter:
KeePassTestSuite.exe /pa:GlobalExecutionPath=.\KeePass\KeePass.exe
Start only a specific test case of the test suite:
KeePassTestSuite.exe /tc:AddNewEntry
Start the test suite with generating a zipped report called report.rxzlog:
KeePassTestSuite.exe /zr /zrf:report.rxzlog
Start a specific run configuration of the test suite:
KeePassTestSuite.exe /rc:SmokeTest
Start the test suite with specific data range
KeePassTestSuite.exe /tcdr:AddEntryByRecording=1-2
Test Suite Settings
Open the test suite’s settings dialog by selecting the context menu item ’Properties’ on the test suite root node.
68
Contents
Figure 99: General settings of a test suite
69
Contents
Figure 100: Global parameters table
70
Contents
Figure 101: Report settings
General Test Suite Settings
Name Specifies the name of the test suite (same as shown within the test suite editor)
Description
Description of the test suite (same as shown within the description column of the
test suite editor). Use the HTML text editor to format the description and to add
links to the description. The formatted description will be represented as HTML
content in the generated report
Show Progress Dialog Specifies whether a progress dialog should be shown during test suite execution
Report Level Specifies the minimum report level of messages shown with the report file
Warn for unbound variables Specifies whether a warning should be shown for unbound variables
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.
71
Contents
Additional Report Settings
Enable Report Specifies whether a test report should be generated
Report File Directory Specifies the directory for the generated report files
Report File
Specifies the filename generated by the report; the following placeholders
are available: %T Time %D Day %M Month %Y Year %L Run Label
%C Run Config Name %H Host Name %S Test Suite Name %X Test
Suite Result
Auto Save Interval Specifies how often the report file is saved during execution
Timestamp
Specifies whether the timestamp should be computed relative to the test
suite start time or relative to the test module start time or the machine
time should be taken
Compressed Copy Specifies whether a copy of the report should be generated as compressed
folder
JUnit-compatible file Specifies whether a JUnit-compatible file should be generated in addition
to the test report.
Collect screenshots in a subdirectory Specifies whether the created screenshots will be stored in a specific folder
for each report or directly in the report folder
Report Template
Specifies the directory holding customized style files used instead of the
Ranorex default style to present the reports; a new template can be created
by pressing the button ’Create Custom Template’ as explained in ’Create a
Custom Report Template’; an existing template can be chosen by pressing
the button ’Choose Custom Template’
Tracing Screenshot Mode
Specifies whether the screenshots will be captured in foreground (before
action is executed) or background (while action is being executed) or
capturing tracing screenshots is disabled
Quality Specifies the image quality of the captured screenshots
Test Case and Smart Folder Settings
The ’General’ tab of the test case’s or smart folder’s properties dialog is mainly used to setup how a broken test case
or smart folder impacts other test cases or smart folders within the test suite. NameName of the test case/smart
folderDescriptionDescription of the test case/smart folder (same as shown within the description column of the test
suite editor). Use the HTML text editor to format the description and to add links to the description. The formatted
description will be represented as HTML content in the generated reportReport LevelSpecifies the level of messages
written to the report file
Error BehaviorSpecifies the behavior of the test case/smart folder and the test suite in case of on error. For further
information please have a look at the next paragraph.
The following figures try to illustrate several Error Behavior settings:
ˆ Continue with iteration: Ranorex will continue with the next iteration of the current test case or smart folder.
ˆ Continue with sibling: Ranorex will stop executing the current test case or smart folder and continue with
the next sibling test case or smart folder instead.
ˆ Continue with parent: Ranorex will stop executing the current test case or smart folder and continue with
the next parent test case or smart folder instead.
72
Contents
ˆ Stop: Ranorex will abort the test entirely.
Figure 102: Continue with Iteration
Figure 103: Continue with Sibling
Figure 104: Continue with Parent
73
Contents
Figure 105: Stop
Figure 106: Test case/smart folder properties dialog
Use the context menu to change the report level or the error behavior for multiple test cases/smart folders.
74
Contents
Figure 107: Specifying error behavior for multiple test cases
Using Data in Test Suites
As already explained in Lesson 3: Data-Driven Testing you can make your automation data-driven by using variables
in your modules (recordings, code modules) as well as in your repositories.
These variables can be connected to internal or external data sources and parameters.
Different kinds of Data Container
Let’s have a look at the different kinds of data container:
Module Variables:
Variables are the interface between a module and the containing test case or smart folder, or - if module groups are
used - the module group, respectively.
Variables can be used in
ˆ recording modules (as described in section Using Variables within Recordings),
ˆ code modules (as described in section Using Variables with Code Modules) and
ˆ repositories (as described in section Using Variables within the Repository).
After building up the test suite with its test cases as described in the previous sections, the included module variables
can be bound to group variables, constant values, data columns, or parameters.
75
Contents
Constant Values:
Constant values can be used in module groups to hide module variables outside a module group. This can help to
reduce the complexity and increases the clarity of module groups.
For further details have a look at the section about the Module Group Editor.
Group Variables:
In module groups, group variables are the interface between the nested modules and the nesting test case.
For further details have a look at the section about the Module Group Editor.
Data Columns:
The columns of a data connector are called Data Columns and specify the columns from external data sources.
Have a look at the data connectors section (Data Connectors) to get an overview about the different kinds of data
connectors. Data columns can be connected to variables in the data binding dialog of a test case as described in
section Combining Variables with Test Data.
Parameters:
Module variables can also be bound to parameters. A distinction is made between local parameters, which are part of
a specific test case or smart folder and are available in the test case/smart folder and all child smart folders, and
global parameters which are available in the whole test suite.
Unlike local parameters, global parameters can be set from the command line as explained in section Running Tests
via Command Line.
Have a look at the section Combining Variables with Parameters to see how parameters can be connected to variables.
Scope of data containers
Global parameters are available in the whole test suite. This means you can bind global parameters to any module in
any test case or smart folder of a test suite.
Local parameters and data columns of a test case or smart folder are inherited by all child test cases or smart folders.
This means you can bind them to
ˆ any modules contained in the parent test case or smart folder.
ˆ any modules contained in child test cases or smart folders.
The following figure illustrates the scope of different data containers.
76
Contents
Figure 108: Scope of data containers
Green rectangle: Scope of global parameters. Blue rectangle: Scope of local parameters and data columns of
SmartFolder2. Red rectangle: Scope of local parameters and data columns of TestCase2.
This means that you can bind the following parameters and data columns to the modules in TestCase2:
ˆ all global parameters (green rectangle)
ˆ all local parameters and data columns of SmartFolder2 (blue rectangle)
ˆ all local parameters and data columns of TestCase2 (red rectangle)
This is illustrated in the following screenshot:
77
Contents
Figure 109: Data binding dialog of TestCase2
78
Contents
The green rectangle illustrates a global parameter, the blue rectangle a local parameter and a data column of the
smart folder named ’SmartFolder2’ and the red rectangle a local parameter and data column of the test case named
’TestCase2’.
Modify Parameter and Data Column Values
Parameter values as well as data column values can be changed by a module. In order to transfer values from one
module to another, parameter or data column values are updated from their bound module variables once the module
has finished execution.
This means you can freely transfer values within the scope of a parameter or data column.
One example of this application would be to dynamically get a value from the UI which should be reused in another
module as described in the section Types of Action Items addressing the Get Value action or at Accessing Test Case
& Test Suite Context.
79
Contents
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.
Figure 110: Ranorex Recorder integrated in Ranorex Studio
Figure 111: Ranorex Recorder as standalone tool
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.
80
Contents
Figure 112: 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.
Figure 113: Add a new recording to an existing test case
81
Contents
Figure 114: Add a new recording to the selected test case
During the next chapters you learn about the following:
ˆ Before Starting to Record
ˆ During Recording
ˆ After Recording
ˆ Replay and Debug Actions
ˆ Recorder Variables
ˆ User Code Actions
ˆ Additional Editing Options
ˆ Image-Based Automation
82
Contents
Before Starting to Record
Regardless whether you use Ranorex Recorder within Ranorex Studio or as a stand-alone tool, both the Recorder and
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 configure Ranorex Recorder using the settings dialog. Click the
’Settings’ button to open the settings dialog.
Figure 115: Settings for current recording file
83
Contents
Figure 116: Default values used for every new 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.
Description:
Can be used to briefly describe the actions the recording performs.
Recording namespace:
Specifies the namespace used for the generated code.
Recording class name:
Specifies the class name used for the generated code.
Replay speed factor (%):
The speed factor is used to increase or decrease the replay overall speed by a specific factor value.
Replay repeat count:
The repeat count is used to specify the number of iterations.
84
Contents
Recorder UI mode:
By specifying the recorder UI mode the set of actions available in the actions table will be adapted (”Global”: all
actions, ”Desktop & Web”: no mobile actions, ”Mobile”: no mouse and keyboard actions).
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:
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
In this tab you can specify global default values for every newly created recording. The settings are divided into three
sections:
Recording
Capture a screenshot for each step: Specifies whether a screenshot of the current action should be made during
the recording.
Highlight elements: Specifies whether element highlighting during recording should be enabled.
Coordinate recording mode: Specifies the way coordinates will be recorded. Following options are available:
ˆ None: Actions will always be invoked on the ’center’ of the recognized elements
ˆ Pixel: Relative coordinates within a recognized element are recorded in pixels
ˆ Proportional: Relative coordinates within a recognized element are recorded in percent
Timings for new actions
Note: Please note that the following settings only affect newly created actions, not existing actions.
Use timings also for recorded actions: When enabled, the specified timings below will be taken instead of the
recorded durations.
Key sequence split time (ms): Use this setting to specify the maximum time between key presses in a key sequence
during recording. If this time is exceeded, the sequence is split into multiple 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.
85
Contents
Mouse/Pointer-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, when the time of
an action cannot be determined during recording or when ’Use timings also for recorded actions’ is activated.
Keyboard-related action time (ms): Specifies the default overall time in milliseconds used for a manually created
keyboard action. The value set for this setting is only taken into account for manually created actions, when the time
of an action cannot be determined during recording or when ’Use timings also for recorded actions’ is activated.
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.
86
Contents
During Recording
Click the ’Record’ button to trigger a new recording.
Figure 117: Click ’Record’ to start recording
After clicking the record button you’re assisted in running an application, opening a browser to navigate to a particular
URL or starting an app on a mobile device before recording any actions. Therefore it’s not necessary to record actions
like double clicking a shortcut on the desktop. By choosing the option instant recording it’s on you to start the
application under test.
Figure 118: New recording dialog
Figure 119: Start a desktop recording
87
Contents
Figure 120: Start a web recording
Figure 121: Start a mobile recording
After clicking the ’Record’ button, the Recorder or Ranorex Studio will be minimized. A running recording session is
indicated in the Ranorex Recorder tool bar.
88
Contents
Figure 122: 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.
Note: The Recording can be stopped either by using the keyboard shortcut + or by
pressing the ’Stop’ button.
Validation (aka Checkpoint)
The Ranorex Recorder provides two different types of validation during a running recording session:
ˆ Validation based on attribute values of a UI element
ˆ Image-based validation
Note: A validation step is also known as checkpoint.
Screencast: The screencast ”Quick Start with Ranorex Test Automation” provides a short overview, and
among other useful information also shows how to create a validation step during a recording. You can jump
directly to the noted position in the video by clicking http://youtu.be/0S YC7uwI-s#t=2m17s.
Validating States or Attributes
The Ranorex Recorder tool bar can be used to validate states or attributes of GUI elements during a running recording
session. Click the ’Validate’ button to pause the recording in order to start the validation.
89
Contents
Figure 123: Validation mode is active
The 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. Click on the
element to open the validation dialog.
Figure 124: The highlight frame specifies the element to validate
In the Validation dialog you can check if you have chosen the right UI element to validate. By clicking ”Next” button
you can define the attributes and their values you want to validate.
90
Contents
Figure 125: Select the UI element you want to validate
91
Contents
Figure 126: Select the attributes of the UI element to validate
92
Contents
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 hotkeys in the section Recorder Hotkeys later on in
this lesson.
Figure 127: 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.
Figure 128: Validate whether a specific listitem contains a specified image or not
93
Contents
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 ’’.
The recorder’s toolbar will then show which shortcuts are available.
Figure 129: Available hot keys during a recording session
’V’:
Press the hot key ’V’ to turn on Validation (aka Checkpoint) - 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 relation 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 Automation - used for pop-up windows, menu items or drop-down
lists.
’Roll Mouse Wheel’
Roll the mouse wheel during validation mode to change the level of UI element selection.
94
Contents
After Recording
After pressing the ’Stop’ button on the Recorder toolbar, the recorder represents all low level actions like clicking on a
button or typing text within the action’s table.
Figure 130: 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 (Click, Double-Click, Move, etc.) or which button was used (Left, Right, etc.) a key
sequence action only stores the keystrokes made during a recording.
Figure 131: Recorded key sequence action
95
Contents
Figure 132: Recorded mouse click 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.
Figure 133: Key sequence action (at password textfield) refers to the repository item ’Password’
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.
96
Contents
Figure 134: Merging selected keyboard items
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.
Figure 135: 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
at the selected item.
Figure 136: Automatically generated repository
97
Contents
Figure 137: 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.
98
Contents
Replay and Debug Actions
In order to replay all actions as fast as possible, activate ’Turbo Mode’ by clicking the button on the tool bar.
Simply click the ’Play’ button in the recording to replay all actions.
Figure 138: Replay recorded actions
Note: To set the ”Turbo Mode” for more than one module select the desired modules in the ”Module
Browser” and set the option ”Enable Turbo Mode” in the properties pane.
Figure 139
Note: You can specify the report level for the present replay directly in the context menu of the play button.
See Lesson 8: Reporting - Report Levels for more details.
99
Contents
Figure 140: Specify Report Level
During execution, the progress box shown at the right lower corner gives information about the current automation
state. Press the key to stop execution. Press + to skip delays and timeouts during
replaying.
Note: If a test is stopped with the abort key, the teardown region will not be executed.
Figure 141: Test run progress
If the option ’Generate replay reports’ is set to true, a report is shown after replay has finished. By default, each
action item logs one message to the report.
100
Contents
Figure 142: 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 a step causing an
error and quickly re-run single or selected steps using the context menu. Additionally, you can ’play to’ and ’play
from’ the selected item
Figure 143: Play a selected item
101
Contents
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 use variables instead.
Figure 144: Variables used for key sequence actions
The variables in the table above are shown in green. All variables used within the recording can be connected to a
Ranorex data connector or to local/global 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.
Figure 145: Make a key sequence action variable
102
Contents
Figure 146: Create a new variable
Most action types can make use of variables. 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.
Figure 147: Creating a new variable for use within the path of the repository item
103
Contents
Figure 148: Create a new variable for selecting a 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’.
Figure 149: Open the variables dialog in the Recorder
104
Contents
Figure 150: Variable dialog of a recording with different levels of usage
Use the toolbar to add, remove or copy a variable from the repository. Change the name of the variable and set a
default value by clicking in the cells of the table. Press the ’Copy 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.
105
Contents
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 where user code actions could be convenient.
ˆ 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 associated code files.
Figure 151: Recording ’AddEntry’ 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 .
ˆ User specific source code file .UserCode.
You can jump to the generated code of a recorded action by right-clicking the action and choosing ’View Code’ from
the context menu. Alternatively you might use the shortcut + to achieve the same as with the
context menu.
106
Contents
Figure 152: Jump to generated code of a recorded action
Every time you change and save a recording, the main code file ’AddEntry.cs’ is newly generated. Any change of code
should always be made within the recording’s UserCode.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 via
the toolbar button ’Add New Action’.
107
Contents
Figure 153: Convert an existing action item to a code action
Figure 154: Specify method name used for user code item
108
Contents
Figure 155: Use the context menu item ’View 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#
namespace MyFirstTestProject
{
public partial class AddEntry
{
///
/// This method gets called right after the recording has been started.
/// It can be used to execute recording specific initialization code.
///

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 ’ at 175;9.", repo.FormAdd_Entry.
TabPageList.InputFields.TextPasswordInfo);
repo.FormAdd_Entry.TabPageList.InputFields.TextPassword.Click("175;9");
}
}
}
VB.NET
Namespace MyFirstTestProject
Public Partial Class AddEntry
’’’
’’’ This method gets called right after the recording has been started.
’’’ It can be used to execute recording specific initialization code.
’’’

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 ’ at 175;9.",
repo.FormAdd_Entry.TabPageList.InputFields.TextPasswordInfo)
repo.FormAdd_Entry.TabPageList.InputFields.TextPassword.Click("175;9")
End Sub
End Class
End Namespace
109
Contents
User Code Actions and Parameters
With Ranorex it is possible to use parameters for user code actions. You can pass arguments with different types to
your user code methods to gain more flexibility in your testing environment.
Next to passing different types of values it is also possible to pass repository items to user code actions. This enables
e.g. combining several actions on one UI object or building up a generic library of smart actions independent of the
underlying technology to only name some of the potential applications.
To use parameters for a new user code action, click the ’Args’ button next to the method’s cell to open the Argument
Editor.
Figure 156: Open the Argument Editor
By pressing the ’Add’ button, you can choose the type of the argument you are going to pass to the user code action.
Figure 157: Add argument
After adding a new argument, you can edit its properties. To enhance flexibility, you can use variables instead of
hardcoded values.
110
Contents
Figure 158: Edit properties of the argument
After declaring the parameters with values or variables, you can switch to the user code method and use the passed
parameters..
C#
public void AddEntryWithParams(string aTitle , string aUsername , string aPassword , string aURL)
{
// Set text fields
repo.PwEntryForm.Text.TextValue = aTitle;
repo.PwEntryForm.UserName.TextValue = aUsername;
repo.PwEntryForm.Password.TextValue = aPassword;
repo.PwEntryForm.Repeat.TextValue = aPassword;
repo.PwEntryForm.URL.TextValue = aURL;
}
VB.NET
Public Sub AddEntryWithParams(aTitle As String , aUsername As String , aPassword As String , aURL
As String)
’ Set text fields
repo.PwEntryForm.Title.TextValue = aTitle
repo.PwEntryForm.UserName.TextValue = aUsername
repo.PwEntryForm.Password.TextValue = aPassword
repo.PwEntryForm.Repeat.TextValue = aPassword
repo.PwEntryForm.URL.TextValue = aURL
End Sub
You can bind the return value of a user code method by setting the option ’Return Value Variable’ in the properties
pane.
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 overloaded methods.
Figure 159: Choose one of the overloaded method calls
111
Contents
Figure 160: Ranorex Argument Editor with arguments and variable binding from overloaded method
As mentioned above it also is possible to pass repository items to user code actions. This can be accomplished by
either choosing the argument type ’Adapter’ or ’RepoItemInfo’, when adding arguments using the Argument Editor.
After defining the repository item arguments, the can simply be bound to repository items the same way as any other
action in the actions table by selecting them in the action table or dragging and dropping them from the repository.
Figure 161: Repository item as argument for a user code action
After declaring the parameters with repository items, values or variables, you can switch to the user code method and
use the passed parameters.
The following example simulates a keyboard input to the given repository item using the given string value. Followed
by a validation whether the text value attribute of the given repository equals the given string value. After that a
screenshot of the current state of the UI element represented by the repository item will be reported.
C#
public void SetAndValidateTextValue(Ranorex.Adapter repoitem , string val)
{
Keyboard.Press(repoitem , val);
Validate.AreEqual(repoitem.As().TextValue , val);
Report.Screenshot(repoitem , true);
}
VB.NET
Public Sub SetAndValidateTextValue(repoitem As Ranorex.Adapter , val As String)
Keyboard.Press(repoitem , val)
Validate.AreEqual(repoitem .[As](Of Ranorex.Text)().TextValue , val)
Report.Screenshot(repoitem , True)
End Sub
112
Contents
Using repository items as arguments for user code actions enables a variety of possibilities such as providing a
framework of smart test actions, defining generic technology independent get/set value actions, combining several
related actions to one user code action, implementing complex validations and many more.
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.
Note: Only create small and easy to maintain user code actions for a recording. If an implemented method
should also be available for other test cases, create a code module (see Lesson 7: Code Modules) instead.
Within the ’DeleteEntry’ recording that was created in Lesson 3: Data-Driven Testing, there are three simple actions
for 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 an entry if it is selected. To accomplish this, code with a condition can
be used.
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. Click on the ’Merge Items to User Code Item’ menu item in the context menu.
Figure 162: 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 Code’. Now
change the converted code so it is only executed if the cell is focused on.
C#
public void DeleteItemIfFocused(RepoItemInfo cellInfo , RepoItemInfo menuitemInfo)
{
if (repo.MainForm.Entry.HasFocus) {
Report.Log(ReportLevel.Info , "Mouse", "Mouse Right Click item ’cellInfo ’ at Center.",
cellInfo);
cellInfo.FindAdapter ().Click(System.Windows.Forms.MouseButtons.Right , 100);
Report.Log(ReportLevel.Info , "Mouse", "Mouse Left Click item ’menuitemInfo ’ at Center.",
menuitemInfo);
menuitemInfo.FindAdapter ().Click (100);
}
}
VB.NET
113
Contents
Public Sub DeleteItemIfFocused(cellInfo As RepoItemInfo , menuitemInfo As RepoItemInfo)
If repo.MainForm.Entry.HasFocus Then
Report.Log(ReportLevel.Info , "Mouse", "Mouse Right Click item ’cellInfo ’ at Center.",
cellInfo)
cellInfo.FindAdapter(Of Cell)().Click(System.Windows.Forms.MouseButtons.Right , 100)
Report.Log(ReportLevel.Info , "Mouse", "Mouse Left Click item ’menuitemInfo ’ at Center.",
menuitemInfo)
menuitemInfo.FindAdapter(Of MenuItem)().Click (100)
End If
End Sub
114
Contents
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 manually add actions to the actions table. One way is specifying the action itself (’Add New
Action’) and assigning a repository item (in most of the cases) afterwards. The second method is dragging and
dropping the 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 ’Add New Action’ drop-down menu as
shown below:
Figure 163: 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.
115
Contents
Figure 164: 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.
Confirm your selection by clicking OK.
Figure 165: 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’.
116
Contents
Figure 166: 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 ’Click’ to ’Move’.
Figure 167: 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.
117
Contents
Figure 168: 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
Actions used in the actions table can be divided into two groups: Basic and Smart Actions. Basic Actions are
performed by the end user with the keyboard, mouse, on-screen keyboard or touchscreen utilizing the mouse, mouse
wheel, touch, key shortcut, key sequence or mobile key-press. These actions are automatically recorded with the
Ranorex Recorder. All other actions are so-called Smart Actions.
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
Swipe Gesture Adds a new swipe gesture event action item at the current position
Key Shortcut Adds a new key shortcut action item (e.g. ’CTRL+C’ or ’CTRL+V’)
Key Sequence Adds a new key sequence action item (e.g. ’Hello’)
Mobile Key Press Adds a new mobile key press action (e.g. {BACK}, {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
118
Contents
Deploy Android/iOS App
Instruments the given Android application and deploys it on the given mobile
device or deploys the already instrumented iOS application on the given
mobile device
Set Device Orientation Sets the orientation of the device either to ’Portrait’ or ’Landscape’
Close Application Closes an application or web site containing the given repository item
Wait For
Waits for a given repository item to appear or disappear
Note: This action can be used for any type of UI element
Log Message
Adds a new report action item logging a user defined message
Note: In addition to the standard report levels, you can define custom report
levels by changing the level from ’Info’ to ’Custom’
Capture Screenshot Adds a new report action logging a screenshot of a specific repository item
Create Snapshot
Adds a new report action item adding a snapshot file of a specific repository
item
Separator Inserts a separation line on the currently selected position in the actions table
Delay Adds a new delay action item
User Code
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 actions can handle module variables.
Note: Based on the ’Recorder UI Mode’ there will be different sets of actions available. You can change the
’Recorder UI Mode’ in the ’Current Recording’ tab in the settings dialog.
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’, ’Click’, ’Double-Click’ 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 A touch event can be used to perform different kinds of touch events on mobile devices as well as on
Windows 8 desktops. The duration of the different kinds of touch events can be defined in the properties pane. You
can open this pane by clicking the context menu item ’Properties’ on the ’Touch Event’ action item.
119
Contents
Swipe Gesture This action can be used to simulate a swipe gesture on a given repository item. You can specify
the direction and the distance as well as the swipe duration. The distance can either be specified in pixels or as a
percentage relative to the repository item connected to the action. The swipe gesture can only be added manually, it
will not be recorded. Additionally you can set the start location as well as the amount of swipe steps in the properties
pane. The properties pane can be accessed by right-clicking the swipe action and choosing ’Properties’ in the context
menu.
Key Shortcut This action can be used for executing key shortcut actions. Aside from the shortcut itself, it is
possible to specify the events ’Press’, ’Up’ and ’Down’. For this action, a repository item assignment is not required.
Key Sequence This action makes it possible to execute or to simulate a key sequence. 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 not required. To protect proprietary data like passwords you can mask the key sequence by setting the option
’Mask Sequence’ in the properties pane.
Mobile Key Press This action can be used for pressing mobile keys like {BACK} and {MENU}. For more detailed
information please have a look at Android Testing - Record and Run an 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.
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.
120
Contents
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 ’AttributeContains’. 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’ dialog which can be accessed via a button
in the ’Screenshot’ column. You can enable reporting the similarity in the properties pane. This can be useful
for tweaking the similarity of the corresponding image validation action. 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 a better understanding of what is different between the two compared images you can
enable ’Report Difference Images’ in the properties pane. This will report a difference mask showing the differing
pixels as well as the differential image. Additional you can enable reporting the similarity in the properties pane. This
can be useful for tweaking the similarity of the corresponding image validation action. For more information about
image-based validation please see Image-Based Automation later in this chapter.
Example: To validate whether the toolbar of the KeePass application contains the intended icons you can compare
the repository item with a screenshot of the toolbar in its initial state.
Invoke Action 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. You can bind the return value of an invoke action by setting the option ’Return Value Variable’
in the properties pane.
Invoking user-defined (dynamic) actions: In addition to access actions delivered by default, you can also invoke
user-defined actions (see Invoking User-Defined Actions) in your System Under Test.
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 (see figure below).
121
Contents
Figure 169: Submenu for Get-Value action
Parse strings with regular expressions: In the ’Capture Regex’ column of the GetValue action you can specify a
regular expression.
For additional information on regular expressions please consult the corresponding MSDN web site: http://msdn.
microsoft.com/en-us/library/az24scfc.aspx
With this regular expression it is possible to easily parse a string out of the specified field. The matched string will be
saved to the chosen module variable for further use. So far there is no need to write a single line of code. If the
regular expression delivers more than one match, the first match will be stored in the module variable.
Example: If you have a string ’Count: 42’ and you want to return the digits only (42) you can use the following
regular expression: ’ˆCount: ([0-9]*)$’
The first non-trivial group matched by the regular expression is returned. If there are no groups captured the full
match will be returned. In case that there are more grouping constructs in the regular expression, you can mark the
requested group using the following construct ’?<1>’.
122
Contents
Example: If you have a string ’Rows: 23, Columns: 42’ and you want to return the number of columns you can use
following regular expression: ’ˆRows: ([0-9]*), Columns: (?<1>[0-9]*)$’
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 this module.
Figure 170: Text value of a button stored in a variable
To make the value stored in the module variable available to other modules, it’s necessary to bind the variable to a
parameter. By doing so, it can then be bound to variables in other modules.
Figure 171: Two variables are bound to one parameter for passing a variable value from one module to another
Set Value As the action name indicates, this method can be used for setting the attribute 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 shown below.
123
Contents
Figure 172: Submenu for Set Value Action
To protect proprietary data like passwords you can mask the value by setting the option ’Mask Value’ in the properties
pane.
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 preparation 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’, ’Chrome’,
’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 Cross-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 with the filename specified in the column ’File
Name’. You can also pass arguments (column ’Arguments’) and define the working directory.
Run Mobile App When using this action you can specify a ’Device’, an ’App’, and whether the specified app should
be restarted or not. For more information see Android Testing - Record and Run an Android Test for Android testing
or iOS Testing - Record and Run an iOS Test for iOS testing.
Deploy Android/iOS App When using this action, you can specify a ’Device’ and an ’APK/IPA file’. The given
application will be deployed to the given device.
124
Contents
Set Device Orientation When using this action, you can specify the orientation of the device. You can choose
one of the following orientations: ’Portrait’, ’PortraitUpsideDown’, ’LandscapeLeft’, ’LandscapeRight’.
Close Application This action can be used for closing applications and web sites. If the ’Close Method’ is set to
’CloseWindow’, 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 closing the application failed. If ’Close Method’ is set
to ’KillProcess’ the application’s process is killed immediately and the grace period is ignored.
Wait For You can use the ’Wait for’ action to wait until the assigned repository item appears (choosing the option
’Exists’) or does not exist anymore (choosing the option ’NotExists’). You can also specify a ’Timeout’.
Report The Report action is typically used for providing information related to the test report.
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.
If no repository item is assigned, a screenshot of the whole desktop is created and will be passed to the 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. Please mind that the assignment of a repository item is
obligatory for this type.
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’).
Note: This time delay is not scaled with the speed factor and is also present in ’Turbo Mode’
User Code User code actions can be used to execute custom class methods defined in the recording user code file.
User code actions are described extensively in User Code 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 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. The sample project including the source code can be downloaded here: sample-project.
125
Contents
Figure 173: Example (in initial state) with public functionality which will be invoked
C#
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.
Figure 174: Example after clicking the button without using custom ’invoke’ functionality
Ranorex provides the functionality for accessing methods that are declared as public directly within the actions table.
The public method ’MyInvokedAction’ can easily be called using a custom argument value. When adding the new
action it is recommended to keep the application (’InvokeExample’) open because accessible functionality is determined
dynamically.
126
Contents
Figure 175: Submenus for available invoke actions
Even parameters can be easily set in the Ranorex Recorder table.
Figure 176: Setting a parameter for an invoked action
You can also access an attribute editor using the ’Browse (. . . )’ button in the last argument column to get an
overview of available parameters.
127
Contents
Figure 177: Browsing available arguments
Invoking this method causes the text field’s content to be set to the desired value.
Figure 178: 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 ’Continue On Fail’. Set an action item to ’Continue On
Fail’ if, in cases of an error, module execution 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.
Figure 179: Disabled actions are grayed out while ’Continue-On-Fail’ is indicated by an italic font style
Note: In case of an error the particular action logs a warning to the report.
128
Contents
Note: To make a validation action optional you additionally have to set the ’Report Level on Failure’ of the
action to ’Warning’. You can set this option via the property grid.
Splitting 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.
Figure 180: Creates a new Recording from the selected items
Use the test suite editor as described in Lesson 2: Ranorex Modules - Test Actions and Lesson 4: Ranorex Test Suite
to combine multiple recording modules into one test case.
Changing the Repository of a 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.
129
Contents
Figure 181: 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. Creating a new repository for your recording
automatically adds a new repository file to the current project.
130
Contents
Image-Based Automation
In some situations, required information for automation is not available as text but only as pixel image. Ranorex
provides image-based automation to bypass this lack of accessibility.
Screencast: Information about image based automation can also be found in our screencast ”How and When
to Use Imaging Capabilities”. Please follow the link to view this video: http://youtu.be/wwr5ddOe4h0.
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.
Figure 182: ’Image based’ recording activated
Now move the mouse pointer over a certain UI element. Ranorex highlights the UI element below the mouse and also
highlights a recognized image region within the UI element. To turn off image-based recording, uncheck the checkbox
or press the shortcut key ’I’.
Note: Hotkey functionality has to be activated by first using the master hot key ’SCROLL’. Read more about
hotkey usage in the current lesson in the section entitled Recorder Hotkeys.
Introductive Example
In KeePass, 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 lower index can be deleted.
131
Contents
Figure 183: 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 done on the listview control
in contrast to a click on an (icon) element itself because this click defines the region in which the prospective image
has to searched. Thus the image is searched in the entire list control.
After stopping the recording, the actions table contains an image-based mouse click action. At the time of recording
the mouse click, a screenshot of the control was created and is now listed as a child element of the corresponding
repository item.
Figure 184: 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 figure of the listview. Open the image editor by clicking on
132
Contents
the button in the location cell (see graphic above). In this dialog use the ’Select image find region’ toolbar button 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 the Image Editor section.
Figure 185: ’Select image find region’ and ’Select click location’ in Ranorex Image Editor
In this example, Ranorex has been used to automate a mouse click on 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 figure 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’ in the
property grid.
Image-based Location Settings
Advanced Options
Use the property group to set advanced image search options like ’Clipping’ or ’Best Match’ 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 (see table
”Image Preprocessing Filters” below).
Screenshot Name Specifies the name of the screenshot used in the search.
Selection Rectangle Defines the image selection region (= what to search for).
Similarity Specifies the minimum similarity (0.0-1.0), that the image region to search for needs to
have in common with the image in order to be considered a match.
Image Preprocessing Filters
133
Contents
None: No preprocessing
Grayscale: Convert the image to a grayscale image.
Edges: Detect object edges in the image using the
Laplace edge detection algorithm (includes Grayscale).
EdgesSobel: Detect object edges in the image using
the Sobel edge detection algorithm (includes Edges).
Downsize: Downsize the image.
Threshold: Convert the image to a black/white image
using a threshold (includes Grayscale).
Image-Based Settings
To set up the default values for image-based recording, open up the ’Settings’ dialog and continue with activating the
’Imaging’ tab.
134
Contents
Figure 186: 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.
Figure 187: Click location dialog to change the settings of image-based mouse actions
135
Contents
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 Click 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
Capture New Screenshot Captures a new screenshot from the related repository item
Use the drop-down combo boxes to specify whether a mouse action should be performed relative or absolute to the
currently defined ’Image Find Region’.
Absolute location means the distance from the upper left corner of the ’Image Find Region’ to the click location (in
pixels).
Relative location offers a couple of pre-defined location settings (e.g. Center, CenterLeft . . . ) relative to the ’Image
Find Region’. It’s also possible to define relative position statements for the click location. Therefore the click-location
inside the ’Image Find Region’ is defined by a value between 0 and 1 for both directions (X and Y-Axis). A relative
click location of ”0.9;0.9” defines a click near the bottom right corner of the specified region. Values greater than 1
(or negative values) mean locations outside the defined region relative to the size of the region.
Figure 188: Set relative or absolute mouse action location
If the captured screenshot has to be updated, click the ’Capture 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 (checkpoint) or automation actions.
136
Contents
Figure 189: Add a new image or select an existing image to specify the location/graphic to search
137
Contents
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 Item Properties
138
Contents
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 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.
Figure 190: File view of a repository
Figure 191: Integrated repository view within the Recorder
Screencast: Watch the screencast (http://youtu.be/uYqruaEUcCU) on organizing and optimizing a Ranorex
Repository to find out how to best use simple and rooted folders.
You can access and edit the repository (directly) in the recorder view by double clicking the file (’MyFirstTestProjectRepository.rxrep’) in the projects view as shown in the figures above.
139
Contents
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 to edit the
names.
Figure 192: 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.
Figure 193: Adding a ’Simple Folder’ to the repository
140
Contents
Figure 194: 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:
Figure 195: Ranorex repository structure
Application Folder #1 Represents a top level application, a dialog or a context menu
Rooted Folder #2 Contains GUI elements having the same parent (i.e. RanoreXPath prefix)
Simple Folder #3 Used to group items
Adapter Item #4 Represents a Ranorex adapter (Button, ListItem, TextBox, ComboBox, etc.)
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.
141
Contents
Figure 196: Specify whether to search in ’Names’, ’Paths’ or to ’Search All’ elements
Figure 197: Search result for text ’button’ used in names and paths
Repository Cleanup
The repository’s ’Cleanup’ button is used to search for currently unused items and to delete these items afterwards.
Unused items mean they are neither used by recording modules nor by code modules.
Considering the situation that a user clicked unintentionally on some desktop icons during the recording, these icons
would have been added to the repository as well. Cleaning up would be beneficial in that case.
Another situation where cleaning up is helpful is when UI elements which are still linked from the repository are no
longer part of the software under test.
In order to keep your repositories as tidy as possible, use the ’Cleanup’ functionality from time to time to avoid
disorder.
Figure 198: The ’Cleanup’ button
In the ’Cleanup’ dialog unused repository items are listed and checked automatically. Uncheck items if you do not
want to delete them.
142
Contents
Figure 199: After clicking the ’Cleanup’ button a dialog is shown with the repository elements currently not in use by
any of recording or code modules within the project
143
Contents
Note: The cleanup functionality only searches for used items in the solution the repository is located in.
There is no check if items are used in other solutions referencing the repository.
Find Repository References
In Using Repository within Code Module 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 which code files use that item. Use the context menu item ’Find All Code References’ to list all code files using
a certain repository item. You can choose whether to search in all the code files or only in the user code files.
Figure 200: Search for references of repository item KeePass
Figure 201: Search result - simply double-click a result item to open the code file
Next to finding repository items in code you can also search all test modules.
144
Contents
Figure 202: Search for references of a repository item in all test modules
Figure 203: Search result - simply click a result to open the test module
145
Contents
Adding Repository Items
Screencast: In addition to going through the explanations on the following pages, you can get a good
overview of ”Adding Repository Items” by watching our screencasts on this topic. How to add items manually
is explained here: http://youtu.be/C1AVdFbUlIo. Several ways to use the Ranorex Spy tool are pointed out
in this video: http://youtu.be/p25kFcjcuBs.
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 the UI element the action should be executed on. 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.
Figure 204: 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. Successful identification is indicated
by a highlight frame around the button.
Figure 205: Track and identify the ’Find’ button with Ranorex Spy
146
Contents
As a third step, add the button to the repository as shown in following figure.
Figure 206: Add the item to the currently open repository
Note: Alternatively you can drag and drop the item from Ranorex Spy directly into the repository from
Ranorex Studio.
Figure 207: Newly created item in the repository
Note: It is also possible to track UI elements directly from the repository using the Track button.
147
Contents
Figure 208: Tracking directly from the repository
Now the ’Find’ button is part of the repository and is ready to be used by code or recording modules. Create 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
ˆ Click on the ’browse repository button’ in the recording grid (column for repository item)
Figure 209: Connect repository item to action using the browse repository button
Alternatively you can 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).
148
Contents
Figure 210: Context menu for choosing action type 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 similar to the steps already done in this section.
ˆ Open the Ranorex Spy tool (if not already opened)
ˆ Track the ’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 (e.g. FindText)
ˆ Add a new action (’Mouse’) to the recording in Ranorex Studio
ˆ Connect this action to the repository item ’FindText’
ˆ Add a new action (Key Sequence) to the recording
ˆ Change the value in the column ’Sequence’ to a text phrase that you want to search for (e.g. WordPressDemo)
ˆ Connect 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
149
Contents
ˆ Connect this action to the repository item ’Button Find’
Note: This long list of steps shows the manual method of creating a recording. Of course these steps could
be also done as a normal recording without worrying about assigning 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’, ’Play To Here’ or ’Play From Here’.
Figure 211: Execute a 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: It is also possible to add a recording module two or more times to a test case. See the following
example for more details.
A More Advanced Test Case Example
Within this test case it may be a good idea to combine the ’FindEntry’ module with the ’Validate’ module. The test
case structure in the following figure would extend the current example with a more complex combination of modules:
Figure 212: 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 (’StartAndLogin’) 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 (’AddEntry’) the second instance of the ’Find’ module with
the subsequent ’ValidateEntry’ 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 ’SaveAndClose’ module group is executed anyway.
150
Contents
Note: To prevent the recorder from stopping the run on failing the validation (intentional) please have a
look at Lesson 5: Ranorex Recorder - Continue On Fail and Disable and enable continuing on fail.
Repository Items Representing Multiple Elements
You can create a repository item using a RanoreXPath which 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 representing a single checkbox each.
Figure 213: RanoreXPath delivering multiple results (All buttons from the toolbar in KeePass)
Screencast: This scenario is presented in the screencast ”Code Modules - Benefits and Use Cases”. Please
follow the link to watch it now: http://youtu.be/4k-lcNxQd2U#t=3m28s it will open at the position in
which this topic is covered.
Use the Ranorex Spy to prepare a RanoreXPath with multiple result elements and add it to the repository as described
in the previous section.Repository items delivering a list of elements can be used in code modules as described in
Create a List of Adapters From a Repository Element.
151
Contents
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.
Figure 214: KeePass application opening a new database 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 specific timeout
value. Use the context menu item ’Properties’ to open the properties for the application folder for the ’Log In’ dialog.
152
Contents
Figure 215: 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.
Figure 216: Test case execution failed - ’LoginWindow’ was not found within the specified timeout of 10ms
Note: In order to restore your repository into a working condition, 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. ’ClipBoardTestCase’) containing the recording modules ’StartSUT’, ’Login’ as well as ’Save’ and ’CloseSUT’. Between those
two blocks insert a new recording module ’ValidateClipBoard’.
153
Contents
Figure 217: 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 ’Instant Recording’ and complete the following steps)
ˆ Click the ’Validate’ button in the Ranorex Recorder tool window
ˆ Validate the status text ’Ready’ after the highlight frame appears
ˆ Confirm the ’Validation’ dialog
ˆ Click on any item in KeePass
ˆ Open the context menu and choose ’Copy Password’
ˆ Click the ’Stop’ button in the Ranorex Recorder tool 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.
154
Contents
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 required for 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.
Figure 218: RanoreXPath separation
Press to change the RanoreXPath expression of an item using the edit mode or open the Path Editor by
clicking the ’Edit’ button.
Figure 219: ’Edit’ button opens Ranorex Spy
155
Contents
Figure 220: 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, 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 9: Ranorex Spy - The Path Editor.
After changing the identification attribute from ’AccessibleName’ to ’Text’ you can quickly verify the new RanoreXPath
using ’Highlight element’ as shown below.
Figure 221: Highlight the modified element to check the modified path
156
Contents
Figure 222: Save button as highlighted element
157
Contents
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
ˆ Common Repositories for Common Modules
ˆ Advanced RanoreXPath Repositories for Complex 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 exclusively 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
Repositories can (and should) be modularized and reused in the same way recordings and code modules are. 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, commonly available controls, and should be based on a
repository which exclusively represents commonly used controls on the user interface.
Advanced RanoreXPath Expressions
Another reason to build a separate repository could be to store advanced RanoreXPath expressions which should
exclusively be used to create new actions manually instead of recording them.
Multiple 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.
158
Contents
Figure 223: Create a new repository file
Figure 224: New repository representing the complex options dialog in KeePass
Screencast: There is a screencasts that specifically explains why and how to use multiple repositories in a
single Ranorex Project. You can find that video here: http://youtu.be/WYlGt-IG5Uo.
Note: It’s crucial to understand that repositories are essential in working with Ranorex and that the basic
principle does not depend on the technology used.
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 and combined within one test automation project in Ranorex Studio.
Using Multiple 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.
159
Contents
C#
[TestModule("C5B0C011 -274A-4E54 -83DB -0 CE28DB95509", 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;
///
/// Constructs a new instance.
///

public OptionsCodeModule ()
{
// Do not delete - a parameterless constructor is required!
}
///
/// Performs the playback of actions in this module.
///

/// You should not call this method directly , instead pass the module
/// instance to the method
/// that will in turn invoke this method.

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;
}
}
VB.NET
_
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
’’’
’’’ Constructs a new instance.
’’’

Public Sub New()
’ Do not delete - a parameterless constructor is required!
End Sub
TestRepository repo = TestRepository.Instance;
’’’
’’’ Performs the playback of actions in this module.
’’’

’’’ You should not call this method directly , instead pass the module
’’’ instance to the method
’’’ that will in turn invoke this method.

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
160
Contents
Repository Settings Dialog
There are two ways to open the ’Settings’ dialog for the repository:
ˆ Clicking the ’Settings’ button within Ranorex Spy
ˆ Clicking the ’Settings’ button within Ranorex Recorder
Figure 225: Open ’Settings’ from Recorder
Figure 226: Open ’Settings’ from Spy
Within the ’Current 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 class name and namespace of newly created
repositories. Additionally, the timeouts used for newly created repository folders and items can be changed in the
’Timings for new entries’ group box.
The setting ’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.
Figure 227: Current settings of a repository
161
Contents
Figure 228: 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 ancestor folders by
setting the ’Use Cache’ property to ’False’.
162
Contents
Repository Item 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 properties tab which can be accessed by right-clicking the desired
repository item and choosing ’Properties’ in the context menu.
Figure 229: Opening the repository item’s properties
163
Contents
Figure 230: Repository item properties
Within the properties tab the following properties are available:
Absolute Path The ’Absolute Path’ represents the path to the repository item including the paths of all
parent folders. This property is read-only.
Adapter Type 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 property to default.
Effective Timeout The ’Effective Timeout’ property represents the sum of the search timeouts for the specific
repository item and all its parent folders. This property is read-only.
Comment Using the comment property, the repository item can be described textual.
Live Element The ’Live Element’ represents the element specified by the repository item found in the live
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 an exception is thrown.
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:
164
Contents
Use Cache The ’Use Cache’ property will either enable or disable caching for the specific folder. The chapter
Repository Troubleshooting - Folder Caching will give more information about folder caching.
165
Contents
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.
ˆ Creating Code Modules
ˆ Using Repository within Code Module
ˆ Accessing Screen Shots within Code Modules
ˆ Using Variables with Code Modules
ˆ Using Code Modules within Test Cases
Screencast: In addition to going through the explanations below, you can have a look at the screencast
”Code Modules - Benefits and Use Cases” which provides a good overview of reasons for switching to the
code level and how do this well. The screencast can be found here: http://youtu.be/4k-lcNxQd2U
Creating Code Modules
Create a new code module by clicking the ’Add Code Module’ button at the toolbar.
Figure 231: 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.
166
Contents
Figure 232: Adding a new code module using the context menu
Figure 233: Specifying the name used for the code module
After clicking the ’Create’ 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#
namespace KeePass
{
///
/// Description of AddCredentialEntry.
///

[TestModule("03F5603B -0DDC -49AA -8C26 -4 D8088260C66", ModuleType.UserCode , 1)]
public class AddCredentialEntry : ITestModule
{
///
/// Constructs a new instance.
///

public AddCredentialEntry ()
{
// Do not delete - a parameterless constructor is required!
}
///
167
Contents
/// Performs the playback of actions in this module.
///

/// You should not call this method directly , instead pass the module
/// instance to the method
/// that will in turn invoke this method.

void ITestModule.Run()
{
Mouse.DefaultMoveTime = 300;
Keyboard.DefaultKeyPressTime = 100;
Delay.SpeedFactor = 1.0;
}
}
}
VB.NET
Namespace KeePass
’’’
’’’ Description of AddCredentialEntry.
’’’

_
Public Class AddCredentialEntry
Implements ITestModule
’’’
’’’ Constructs a new instance.
’’’

’ Do not delete - a parameterless constructor is required!
Public Sub New()
End Sub
’’’
’’’ Performs the playback of actions in this module.
’’’

’’’ You should not call this method directly , instead pass the module
’’’ instance to the method
’’’ that will in turn invoke this method.

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#
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;
168
Contents
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
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 to refer to the repository in order to reuse some of the objects (’Title’, ’Username’,
’Password’, ’PasswordRepeat’ and ’URL’) within the ’Run’ method.
169
Contents
Figure 234: 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#
var ButtonOK = MyRepo.FormAdd_Entry.ButtonOK;
ButtonOK.Click();
VB.NET
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.
Accessing Screen Shots within Code Modules
Starting with Ranorex 3.3 it’s possible to access screen shots directly in code using the Info object of a repository item.
This can be useful if you are going to compare a captured screen shot with the actual appearance of your application
under test, for example.
Note: Screenshots will be captured automatically if you chose to record image based. Get more information
here: Image-Based Automation.
170
Contents
Figure 235: Screen shot captured in repository
C#
// get the screenshot from the repository
Bitmap MyScreenshot = MyRepo.IconPicker.LI_IconInfo.GetScreenshot_Icon ();
// create FindOptions with similarity set to 95%
Imaging.FindOptions MyFindOptions = new Imaging.FindOptions (0.95);
// compare the captured screenshot with the actual list item
Validate.CompareImage(MyRepo.IconPicker.LI_Icon , MyScreenshot , MyFindOptions);
VB.NET
’ get the screenshot from the repository
Dim MyScreenshot As Bitmap = MyRepo.IconPicker.LI_IconInfo.GetScreenshot_Icon ()
’ create FindOptions with similarity set to 95%
Dim MyFindOptions As New Imaging.FindOptions (0.95)
’ compare the captured screenshot with the actual list item
Validate.CompareImage(MyRepo.IconPicker.LI_Icon , MyScreenshot , MyFindOptions)
Note: Using the FindOptions, you can set custom values like ’similarity’. This option allows you to define
the minimum similarity that the image region to search for needs to have in common with the screenshot in
order to be considered a match. For further details have a look at Lesson 5: Ranorex Recorder - Image-Based
Automation.
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’.
171
Contents
Figure 236: Add a new variable to your code module
Figure 237: Specify the variable name and the default value
By adding a new variable Ranorex Studio inserts a new code fragment at the current cursor position. A variable implementation consists of a public property ’’ and a private member ’ ’.
C#
string _varTitle = "Wordpress Credentials";
[TestVariable("9348A7E6 -80B6 -4A2B -9CBF -0276 A236AA3E")]
public string varTitle
{
get { return _varTitle; }
set { _varTitle = value; }
}
VB.NET
Private _varTitle As String = "Wordpress Credentials"
_
Public Property varTitle () As String
Get
Return _varTitle
End Get
Set
_varTitle = value
End Set
End Property
172
Contents
Now create additional variables for the ’Username’, ’Password’ and ’URL’. All the module variables will appear
immediately in the module browser.
Figure 238: Module variables are shown in the 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 property. 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 assigning the passed value to the repository variable and facilitates binding to external data.
C#
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";
173
Contents
[TestVariable("D0A54427 -68FF -4B9D -B861 -4882 BCEC846B")]
public string varRepoExpires
{
get { return _varRepoExpires; }
set {
_varRepoExpires = value;
// Additionally set the Repository Variable in Setter -Method
MyRepo.varExpires = _varRepoExpires;
}
}
VB.NET
Private _varRepoIconIndex As String = "1"
_
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"
_
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
Thus the two columns in the Excel file can be bound to these module variables. This binding causes the variables
to be set for each iteration in the test case. When setting those variables, the extended functionality also sets the
repository variable assuring that the correct icon will be used and clicked in our example.
Using Code Modules within Test Cases
The code module implemented above is now ready to be run by a test case. Add a new test case (’TC AddEntryFromCode’) 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 drag and drop to quickly insert the newly created
code module into the test case.
Figure 239: Drag and drop the code module into a test case and combine it with recordings
174
Contents
Now you can reuse the existing data connector created during Lesson 3: Data-Driven Testing with your new test case.
Figure 240: Reuse the existing data connector by choosing the item from the drop-down
175
Contents
Figure 241: Bind the newly created variables to the data connector’s columns, i.e. columns from the Excel file
176
Contents
Lesson 8: Reporting
By default, each run of a test suite, test case, smart folder, or single module 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:
ˆ JUnit-compatible reports
ˆ Progressive report preview
ˆ Reading Ranorex Reports
ˆ Report Levels
ˆ Logging Individual Information
ˆ Updating the Custom Report Format
ˆ Create a Custom Report Template
JUnit-compatible reports
In Ranorex 7.0 and above, you can automatically create JUnit-compatible reports for use in CI tools. Simply check
the option ”Create a JUnit compatible copy of the Report” as shown in the picture below. For more information,
please refer to the reporting chapter in Lesson 4.
177
Contents
Figure 242: JUnit-compatible reports
178
Contents
Progressive report preview
Since Ranorex 6.1 you can catch the progress of the report of a long test run. So you do not have to wait for the
final report at the end of the test and can follow the progress.
Reports are auto-saved during test execution in the report folder and you can open it from there without any worries.
By default a report is created in the directory of the test executable. Just open up a file explorer and switch to this
directory. From there just open the report file you want to preview. If you have specified your own report directory,
you will start the preview from there.
If you open a report which is in progress, an indicator is shown expressing the preview state of the report. To get an
update of the report you can manually refresh it or close and re-open the file.
In the following picture you can see how a progressive report is indicated and the refresh button.
Figure 243: Progressive Report Preview indication
The auto save interval for a report is configured in the properties of the test suite. Open up the properties of the
current test suite and switch to tab page ”Report”. In field ”Auto Save Interval” you can set the interval in seconds.
179
Contents
Figure 244
180
Contents
In case you execute a test module, which is in a project without a test suite, the auto save interval is 30 seconds by
default.
Reading Ranorex Reports
After executing a test suite in Ranorex Studio the generated report file is opened in a file view as shown below.
Figure 245: 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 containers (test
cases, smart folders) have been executed successfully, have failed, or have been blocked. Each executed test container
and all its child modules can be analyzed in depth by expanding a particular test container. The pie chart in the
upper right only represents the successful, failed, and blocked test cases, not smart folders.
In addition to that, a test suite report also informs you about the following:
ˆ System information like execution time, machine name, operating system, screen dimensions, language, duration,
total errors, total warnings
ˆ Global parameter values
ˆ Run iterations and data iterations
Run iterations are indicated by the ”Iterations: #” and ”Run #” labels next to test containers. ”Iterations: #” tell
you how many times the test container will be run. Each sub item of the test container represents a single iteration.
The number of the iteration is indicated by the ”Run #” label next to it.
181
Contents
Data iterations are indicated by the ”Rows: #” and ”Data Row: #” labels next to test containers. ”Rows #” tell
you for how many data rows the data container will be iterated. Each sub item of the test container represents an
iteration for a single data row. The number of the data row is indicated by the ”Row #” label next to it.
If a test case or smart folder uses local parameter values or external test data, the report shows the values used during
automation as shown below.
Figure 246: Detailed view of a report
The detailed 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
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/test case/smart folder and analyze with Ranorex Spy
Expand the report as shown above and move the mouse pointer over the first log message.
Figure 247: Debug a test run with quick links ’Jump to Item’ and ’Open in Spy’
Click at ’Jump to item’ to open the module and to select the corresponding action. 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. Move the mouse cursor over a test case or
smart folder and click on ’Jump to test case/smart folder’ to select in the test suite.
182
Contents
Filter Log Messages
Use the checkboxes shown at the top of each module to filter log messages.
Figure 248: Filter for different log levels
Report Folder
For each run of a test suite, a single test case/smart folder or a module, 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.
183
Contents
Figure 249: 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, it is recommended to use the zipped
report as described in ”Lesson 4: Ranorex Test Suite - Test Suite Settings”.
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.
Report Levels describe the importance of a message that is delivered to the report. Using different kinds of report
levels can help you keep your reports short and better readable.
Within a test suite or even within a test case/smart folder, 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 or smart folder’s report level could assist you in finding errors in your testing scenario.
Predefined Report Levels
Ranorex provides the following predefined report levels - the level itself is indicated by integer values (which are
written in parenthesis):
ˆ Debug (10)
184
Contents
ˆ Info (20)
ˆ Warning (30)
ˆ Error (40)
ˆ Success (110)
ˆ Failure (120)
The first five items describe different levels of importance for report messages. 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.
Figure 250: Report indicating a failed module
Additionally, at the top of a test container, warnings are indicated using a message with a yellow background.
Figure 251: A message indicating the existence of warning messages inside a smart folder
Note: A test container’s failure depends on the success of its child elements which can either be modules
or other test containers (within the rules of the General structure of a test suite). A module fails when an
exception is thrown or a failure message is being logged. Exceptions are typically thrown by failed validation
actions, by searching for nonexistent elements or by an explicit call at code level.
User-defined Report Levels
In addition to predefined report levels, you are able to define your own report level with a custom importance value.
You can do that either from code or within the Recorder (see Logging Individual Information for detailed information).
185
Contents
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 the Ranorex ’Report’ class in order to report information at a specific
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 a single parameter, the message text. 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.DefaultCategory’ property.
The category can be seen in a distinct column in the report. The following code lines demonstrate different reporting
methods (and different reporting categories), resulting in the report shown after the code example.
C#
// 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 warning 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
’ 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 warning 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")
186
Contents
Figure 252: Report with different reporting methods and categories indicating the different levels of importance
Note: Please consider that the report information at the failure level provides a screenshot automatically
(if tracing screenshots is enabled). In order to visually retrace the last steps that lead to the current error,
screenshots will be provided for the last three actions.
User-defined Report Levels
You are able to define your own report levels with a custom name and a value for the level:
C#
Ranorex.ReportLevel MyNewReportLevel = new ReportLevel("My low Report Level", 25, null);
Ranorex.Report.Log (MyNewReportLevel , "This is unimportant information");
VB.NET
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 the user-defined report level
should appear in the report as follows:
187
Contents
Figure 253: Report with information for a user-defined level
Current Report Level
Report information will only appear in the report if its report level is higher than or equal to the current report
information level from the parent’s test container. The current report level can also be set using code:
C#
Ranorex.Report.CurrentReportLevel = Ranorex.ReportLevel.Parse("Only Highest Importance ;90");
VB.NET
Ranorex.Report.CurrentReportLevel = Ranorex.ReportLevel.Parse("Only Highest Importance ;90")
This assignment causes the inclusion of reporting information only at a level greater than 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.
188
Contents
Figure 254: 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#
Ranorex.Report.Log (Ranorex.ReportLevel.Always , "User", "Any -Case message");
VB.NET
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#
Ranorex.Report.Screenshot (MyRepo.KeePass.Toolbar.Self);
VB.NET
Ranorex.Report.Screenshot(MyRepo.KeePass.Toolbar.Self)
189
Contents
Figure 255: 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. Controlling your application using code does not necessarily bring your application to the front and
make it 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.).
Consequently, 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#
Ranorex.Report.SystemSummary ();
VB.NET
Ranorex.Report.SystemSummary ()
Figure 256: System summary provided by Report.SystemSummary()
190
Contents
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 ’LogMessage’ Action.
Figure 257: Add a new log message 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 actions
table.
191
Contents
Figure 258: Define the report level
Custom Report Level
Report messages with a custom report level can also be submitted. Simply type the custom report level into column
’Level’ in the action table following this format: name for the custom report level, a semicolon, and the priority as a
number.
To use a custom report level named ’Custom’ with priority 50 type: Custom;50
Figure 259: 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
actions table. These two actions require a connection to a repository item in order to specify from which object the
screenshot or snapshot should be made.
Figure 260: Usage of the report action using the screenshot and the snapshot action type
Updating the Custom Report Format
Ranorex 4.0.0
Starting with Ranorex 4.0.0 the custom report format has been changed from one single file to a template folder
holding all necessary files. After upgrading to Ranorex 4 and opening a solution using custom reports, a warning will
appear in the Error pane.
192
Contents
Figure 261: ReportXmlFile is no longer supported
Clicking on the warning will open a resolve dialog. In this dialog you can choose to either copy the custom report to a
template folder and use this folder as report template, or to use the default report template.
Figure 262: Choose resolve option
Ranorex 7.0
Please refer to the online guide on upgrading custom report templates created in versions before Ranorex 7.0.
Create a Custom Report Template
To create a custom report template, open the test suite’s properties dialog, navigate to tab page ’Report’ and click
the ’Create Custom Template’ button in the ’Report Template’ area.
193
Contents
Figure 263: Create a custom report template
A new report template folder has automatically been created at ’\NewCustomTemplate’.
The newly created files can be shown in project view by pressing the ’Show All Files’ button.
Note: Press the ’Refresh’ button to ensure that the new created folder will be shown.
Figure 264: Show all files in project view
Open the file ’RanorexReport5.css’ to edit the style of the report according to your wishes.
194
Contents
Note: It’s recommended to make customizations at the end of the file.
Open the file ’RanorexReport5.xsl’ to edit the structure of the report according to your wishes.
Open the file ’View.rxlog’ to get a preview of your customizations using some sample data.
Figure 265: Preview of customizations
195
Contents
Lesson 9: Ranorex Spy
As a stand-alone tool the Ranorex Spy provides all the functionality needed to explore and analyze desktop and mobile
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 and mobile devices.
Figure 266: Ranorex Spy - applications and their UI elements
ˆ Tracking UI Elements
ˆ RanoreXPath Edit Mode
ˆ The Path Editor
ˆ Creating Ranorex Snapshot Files
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 an adapter as described in 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 ’Control’, ’Accessible’ or ’NativeWindow’
196
Contents
Figure 267: 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 as explained in Ranorex UI Adapter. These adapters are also used within repositories and provide class
specific attribute values like the text value or the state of a checkbox.
Technology related adapters like ’Control’, ’Accessible’ or ’NativeWindow’
This type of adapter is used to group technology related information like the ’ControlName’ 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
197
Contents
attribute values at Create Adapters to Access More Properties and Methods.
In addition all attributes can be used within the RanoreXPath. By default the attribute in the overview tab written in
bold is automatically used to identify the UI element.
Figure 268: 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 The Path Editor to change element identification or edit the path
expression directly within the text box’s RanoreXPath Edit Mode.
Note: You are able to access common text functionality like ’Select All’ (+A), ’Copy’ (+C),
’Cut’ (+X), ’Paste’ (+V), ’Undo’ (+Z) or ’Delete’ () in RanoreXPath.
Another way to navigate through the element tree is to use the image navigator which can be found at the bottom of
the Overview/Detail tab.
198
Contents
Figure 269: Image navigator
At the top of the image navigator you can see the adapter type and the name of the currently selected UI element.
By moving the mouse over a specific child element of the currently selected element, you will see the adapter type
and its name. Clicking a UI element selects it, double-clicking outside the selected element selects the parent.
Short Introduction to the Structure of RanoreXPath
The RanoreXPath is built up in a hierarchical way where all the UI levels are separated with a ’forward slash’ (/). The
following figure shows an abstract illustration of how UI levels are represented by so called adapters (e.g. form, button,
etc.). Since there may be more than one UI element 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 using one or more predicate expressions.
You can also specify the intended adapter with the use of an index (e.g. button[2]). As already mentioned, search
specification is commonly done with one or more attributes, where the attribute is prefixed with an @ sign followed by
a comparison operator (=, !=, ∼, > as well as >, >=, <, <=) and an attribute.
199
Contents
Figure 270: Abstract illustration of the structure of RanoreXPath
Attribute comparisons 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 ’Capture Screenshot’ to create an image file (PNG format) which can be used to search
for images in test automation code as explained in How to find and compare images.
200
Contents
Figure 271: 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.
Figure 272: Select an image region to save
201
Contents
Toolbar shortcuts
Browse Endpoint Shows currently running applications on the active endpoint (set as Endpoints)
Endpoints Opens the Endpoints pad
Refresh Updates the current state of applications
Load from Snapshot Loads an existing Ranorex snapshot file
Save as Snapshot Saves the currently selected node and all its descendants to a Ranorex snapshot file
Highlight Elements When switched on, highlights selected UI elements on the users desktop
Update Path Sets the path from the currently selected element
Context menu
Update Path Sets the path from the currently selected element
Set Element as Root Sets the currently selected element as root element
Highlight Element Highlights the current element
Add to Repository Adds the current element to a Ranorex Repository
Add to Repository (incl. Children) Adds the current element and the element’s children to a
Ranorex Repository
Add Matching Children to Repository Adds all UI elements matching the given RanoreXPath
to the Repository
Update Element Data Updates all attributes of the specified UI element
Save as Snapshot. . . Saves the current UI element including the child structure
to a Ranorex snapshot file
Capture Screenshot. . . Captures a screenshot from the current element to be
used for further image-based validation
Expand All Expands all child elements of the selected UI element in
the element browser
Collapse All Collapses all child elements of the selected UI element in
the element browser
Add Class or Process Name to GDI Capture List
Specifies whether the element’s class or process name
should use the GDI plug-In to turn on text-based object
recognition
Actions to perform Based on the type of the UI element a list of different
actions to perform on the UI element is available
202
Contents
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 How
to do image based automation and How to find and compare images.
203
Contents
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 TRACK Button
ˆ Instant Tracking
Using the TRACK Button
Click the ’TRACK’ 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.
Figure 273: Click the ’Track’ button to start element tracking
Note: To abort the tracking session press or click the ’TRACK’ button again.
Note: Holding the key temporarily disables the tracking mechanism.
In some cases it might be necessary to track UI elements which are currently behind the Ranorex Spy window. Simply
uncheck the ’Always On Top’ checkbox to cause Ranorex Spy to minimize during the tracking process.
204
Contents
Figure 274: ’Always On Top’ checkbox within Ranorex Spy
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 + key combination to
instantly track the UI element. ’Instant Tracking’ is not only available for popup items, it can be used for any UI
element.
Figure 275: Instant tracking of menu items
205
Contents
RanoreXPath Edit Mode
There are two ways to change the RanoreXPath expression. One is to work with the The Path Editor. 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 help with text entry. By pressing the key combination + at
any time, the RanoreXPath editor suggests a list of suitable keywords, attributes or operators.
Figure 276: RanoreXPath auto completion
The RanoreXPath editor mode is indicated by a yellow background color. In edit mode, RanoreXPath is used as a
query to filter UI elements as follows:
206
Contents
Figure 277: 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 Children to Repository’.
207
Contents
Figure 278: Add matching items to the repository
To stop the edit mode, click the red cancel button which is located in the RanoreXPath edit box or press the
key.
208
Contents
Figure 279: Leave RanoreXPath edit mode
209
Contents
The Path Editor
In this section you will learn about
ˆ How to Access the Path Editor
ˆ Layout of the Path Editor
ˆ The Tree View Section
ˆ The Attribute Comparison Section
ˆ Types of Comparisons
ˆ Relationship Operators
ˆ Adapter Types
ˆ Optional Path Elements
ˆ Defining Variables
ˆ Live View with Dynamic Capabilities and Offline View
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 have a look at the section ’RanoreXPath’.
How to Access the Path Editor
It’s this easy: Everywhere a RanoreXPath is visible in a Ranorex Tool you can edit this RanoreXPath with the path
editor.
You can access the path editor by choosing any UI Element in the repository and then clicking the ’Edit button’ on
the left of the RanoreXPath, or alternatively by pressing the key shortcut .
Figure 280: Click the ’Edit’ button to open the path editor
In Ranorex Spy, the path editor can be accessed by simply switching to the ’PATH EDITOR’ tab.
210
Contents
Figure 281: Switch to path editor tab
Layout of the Path Editor
The editor can be broken down into two main areas: the RanoreXPath shown in a tree view on the left (marked in
green) and the attribute comparison list of the selected tree item on the right (marked in red).
211
Contents
Figure 282: Overview of path editor
Additionally you can see the number of identified UI elements using the given RanoreXPath in the status bar. Buttons
to refresh and to highlight the identified elements can be found right above the tree view and the original RanoreXPath
can be found at the top of Ranorex Spy, right below the modified one.
As you can see, the whole path is shown in this tree structure with each path element being a node of the tree. In the
left section of the editor, you can access each of these path elements to alter the attribute comparisons in the right
section on which the path is based.
After altering the RanoreXPath, you can review the effects by pressing the refresh and highlight buttons and apply
the changes using the ’Apply’ button next to the RanoreXPath at the top of Ranorex Spy.
Of course you can change the RanoreXPath by using the ’Track’ button, too. To simplify tracking, the tracking area
is limited to the parent folder of the selected repository item (grayed out in RanoreXPath at the top of Ranorex Spy),
which will be indicated with a yellow border.
212
Contents
Figure 283: Tracking area limited to the KeePass application
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 path editor:
213
Contents
Figure 284: KeePass with one cell being tracked by Ranorex Spy
Figure 285: RanoreXPath structure in path editor for a cell in second row
214
Contents
The Attribute Comparison Section
In the attribute comparison section of the path 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.
Concerning 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:
/form[@controlname=’MainForm ’]/ container[@controlname=’m\_splitHorizontal ’] //table[
@controlname=’m\_lvEntries ’]/row[@index=’1’]/cell[@text=’Ranorex ’]
What we can see in the RanoreXPath structure (in path editor) as well as in the RanoreXPath itself is that the row
(adapter) is identified by its ’index’ attribute (row[@index=’1’]). This means that the cell ’Ranorex’ is only recognized
if it is located in the second row. This cell would not be found if an additional row was inserted above and the
index was changed. Sorting by a column (e.g. column username) could easily lead to another row index. To avoid a
problem concerning the row index, you could change the path with the use of the path editor to be row independent
by unchecking the index attribute checkbox in the row node.
Figure 286: Uncheck the index attribute in the row node
/form[@controlname=’MainForm ’]/ container[@controlname=’m\_splitHorizontal ’] //table[
@controlname=’m\_lvEntries ’]/row/cell[@text=’Ranorex ’]
215
Contents
This path leads to any cell in any row containing the text ’Ranorex’. Concerning 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 add the ’column index attribute’ by checking it.
Figure 287: Check the column index attribute
/form[@controlname=’MainForm ’]/ container[@controlname=’m\_splitHorizontal ’]
//table[@controlname=’m\_lvEntries ’]/row/cell[@text=’Ranorex ’ and @columnindex=’1’]
If another KeePass entry is added which has the same username (’Ranorex’), this path would lead to multiple results.
You can easily check the result of your RanoreXPath in path editor by having a look at the text in the bottom left
corner.
216
Contents
Figure 288: The current path leads to two elements
To find out which elements are found with the current RanoreXPath, simply click on the ’Highlight’ button on the
bottom of path editor.
217
Contents
Figure 289: 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.
Types of Comparisons
Ranorex provides a set of comparisons which can be used to build up or to modify a RanoreXPath. These comparison
operators can be accessed via a drop-down in path editor.
Textual Comparisons The following types of comparisons are defined for textual comparisons (case sensitive):
ˆ ’=’: The value of the attribute must be equal to the given value
ˆ ’∼’: The value of the attribute must match the given regular expression
ˆ ’!∼’: The value of the attribute must not match the given regular expression
ˆ ’!=’: The value of the attribute must not be equal to the given value
ˆ ’>’: The value of the attribute must start with the given string
Numerical Comparisons The following types of comparisons 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 comparisons 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.
218
Contents
Example for Regular Expression The following example shows how to use a ’regular expression’ operator (∼).
Figure 290: Matches all entries ending with the text fragment ’rex’ using a regular expression
Figure 291: Result from the comparison above
Note: For more details about regular expressions, see RanoreXPath - RanoreXPath with Regular Expressions.
Example for Not Equal The following example shows how to use the ’not equal’ operator (!=).
Figure 292: Matches all entries that are not equal to ’Ranorex’
219
Contents
Figure 293: Result from the comparison above
Example for Starts With The following example shows how to use the ’starts with’ operator (>).
Figure 294: Matches all entries that start with ’adm’
Figure 295: Result from the comparison above
Example for Numerical Comparisons The following examples demonstrates how numerical operators (>, >=,
220
Contents
Figure 296: Matches all rows matching index > 2 and index <= 3
Figure 297: Result from the comparison above
Relationship Operators
After exploring the comparison operators, you are going to learn more about the relationship operators. Relationship
operators define the relationship between the nodes (elements of the path). It is therefore not necessary to always use
a directed path. One element in the path can also be defined by 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.
221
Contents
Figure 298: Available relationship operators in path 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 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
ˆ 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 change the common parent-child relationship in the path using relationship
operators (’Axis’), 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[@controlname=’m\_splitHorizontal ’] //table[
@controlname=’m\_lvEntries ’]/row[@index=’2’]/cell[@text=’Amazon ’]
222
Contents
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 level manually using the row adapter.
/form[@controlname=’MainForm ’]/ container[@controlname=’m\_splitHorizontal ’] //table[
@controlname=’m\_lvEntries ’]/row[@index=’2’]/cell[@text=’Amazon ’]/row
In the path editor we choose the relationship operator ’parent’ in the ’Axis’ submenu.
Figure 299: 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 level of hierarchy to the
parent of this cell, which is a row. Highlighting the element leads to the result shown in following figure.
Figure 300: Highlighting the element from the newly created path
223
Contents
Adapter Types
Adapters describe the type of element that is referred to. In the path editor you are able to change the adapter type
easily.
Adapters used within a path which are automatically suggested by Ranorex, can also be changed using the context
menu.
Figure 301: Changing the adapter to a specific type of 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.
224
Contents
Figure 302: Windows node located at the root level (left) or. . .
Figure 303: . . . in a sub-node of the tree (right) 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 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.
225
Contents
Figure 304: Marking one level of the path as optional
/form[@controlname=’MainForm ’]// treeitem[@accessiblename=’NewDatabase ’]/ 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 and assigned in the path editor.
If you start the path editor from an existing repository, there is an additional button for each (selected) attribute
comparison. With these buttons you are able to define variables which can be used for data driven object identification.
226
Contents
Figure 305: Buttons for creating a new variable for every selected attribute
227
Contents
Figure 306: Variables can also be created using the ’As new Variable’ entry in the dropdown menu
228
Contents
The variables you have added are placed in the repository you are working on. Each of the variables held by the
repository can be used as a value for attribute comparison. For more details about variables used within the repository,
please have a look at Lesson 3: Data-Driven Testing - Using Variables within the Repository.
Live View with Dynamic Capabilities and Offline View
One additional thing to mention is that if you are in live view, you get more information delivered about the adapter
you are working on than in offline view.
Offline view means working with a snapshot file or working with a repository holding information from a non-running
application.
Note: A Ranorex Snapshot file is able to keep the entire UI structure, the UI element’s attributes and its
belonging values as well as screenshots from the desired element and all its child elements. Learn more in the
chapter: Creating Ranorex Snapshot Files.
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).
229
Contents
Figure 307: Path editor window in live view having dynamic capabilities
230
Contents
Note: Dynamic capabilities can only be accessed for certain types of technologies (WinForms, Flash/Flex,
Web and Java).
231
Contents
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). Create 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 analyze
your application under test offline and give advice on how to optimize unique object identification with RanoreXPath.
Figure 308: Saving the UI structure of KeePass as a snapshot file
232
Contents
Figure 309: Ranorex Spy tool with opened 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 key (keyboard) 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 positioning the mouse
over the edge of the window and pressing +.
4. Press the key to cache the current elements including their underlying items for Ranorex Spy.
5. Lastly save the current view as snapshot.
Another possibility of creating a snapshot from the ’File’ menu pop-up of KeePass is to use the ’TRACK’ button in
combination with the key which temporarily disables the tracking mechanism:
1. Open Ranorex Spy and activate ’Highlight Elements’.
233
Contents
2. Start the KeePass application.
3. Press the ’TRACK’ button.
4. In the KeePass application open the ’File’ menu while holding the key.
5. After releasing the key track the parent menu container window of the menu items using the mouse
wheel to change the recognition level.
6. Reopen the menu and press the key to cache the current elements including their underlying items
for Ranorex Spy.
7. Lastly save the current view as snapshot.
Figure 310: Track menu container window using instant tracking (+)
234
Contents
Ranorex Settings
Settings in Ranorex
Use the Ranorex Settings to adjust the test automation software to the needs of your working environment, test
execution, project and technology.
You can find a full list of settings here: Settings overview
User settings and solution settings
Settings can be divided into two groups: user settings and solution settings. Each setting belongs to one of these
groups.
User settings are always stored locally on a machine and include user specific settings related to the Ranorex Studio
working environment. Find out more here: User settings
Solution settings include all settings which relate to the test solution, such as plugins, RanoreXPath generation,
Ranorex Recorder defaults and many more, which can be shared between different systems, within teams and also be
put under Version control. Find out more here: Solution settings
Where to access settings
There are three ways to open the ’Settings’ dialog:
ˆ Click on the ’Settings’ button within Ranorex Studio.
ˆ Click on the ’Settings’ button within Ranorex Spy.
ˆ Click on the ’Settings’ button within Ranorex Recorder.
To maintain settings (user settings and solution settings) stored locally on a machine, without having Ranorex Studio,
Ranorex Spy or Ranorex Recorder, do the following:
ˆ Start Ranorex Settings application from Windows Start Menu or
ˆ Start the Ranorex Settings executable from folder ’Bin’ in the Ranorex installation directory.
Figure 311: Open ’Settings’ from Ranorex Studio
Figure 312: Open ’Settings’ from Ranorex Spy
235
Contents
Figure 313: Open ’Settings’ from Ranorex Recorder
Figure 314: Ranorex Settings application
236
Contents
User settings
User settings are always stored on the local machine. In the ’Settings’ dialog, user settings are shown in regular font.
At the bottom of the ’Settings’ dialog, a short info text indicates how to differentiate user and solution settings and
the location they are stored in.
Figure 315
237
Contents
Solution settings
Solution settings can be stored either in a solution or on the local machine. In the ’Settings’ dialog, solution settings
are shown in italic font.
At the bottom of the ’Settings’ dialog, a short info text indicates where the solution settings are currently stored.
Figure 316
Solution settings stored on machine
Solution settings are automatically saved to the local machine and used during test execution, if:
ˆ you work in Ranorex Studio and no solution is loaded.
238
Contents
ˆ you work in Ranorex Studio and a solution is loaded, but the solution does not include solution settings.
ˆ you work in Ranorex Recorder, Ranorex Spy or Ranorex Settings (started as standalone tool).
The solution settings stored on the local machine are used as default for newly created solutions in Ranorex Studio.
The info text at the bottom of the ’Settings’ dialog indicates that the solution settings are stored on the local machine
(highlighted in red in the screenshot below).
Figure 317
239
Contents
Solution settings stored in solution
In newly created solutions, solution settings are automatically saved in the corresponding solution settings file and
used during test execution (starting with Ranorex 6.1).
In the following situations, the solution settings are automatically saved in its corresponding solution settings file and
used during test execution:
ˆ Ranorex Studio during test creation and test execution
ˆ ’Settings’ dialog in Ranorex Studio
ˆ Ranorex Spy (as part of Ranorex Studio, opened with ”View Spy” and ”EDIT” at a repository item)
ˆ Settings dialog in Ranorex Spy (as part of Ranorex Studio)
The info text at the bottom of the ’Settings’ dialog indicates that the settings are saved in the solution. The title of
the dialog shows which solution the settings are saved in (highlighted in red in the screenshot below).
240
Contents
Figure 318
241
Contents
Location of the solution settings file
The solution settings are saved in the settings file ’Ranorex.rxsettings’, which is located in the ’Solution Items’ folder
of the corresponding solution.
Figure 319
Please note:
ˆ Do not change the name of the folder or the file.
ˆ If you remove the settings file (”Ranorex.rxsettings”), the solution settings stored on the local machine are
automatically used during test execution.
ˆ If you open the settings file, it is shown in its raw format. It is not recommended to edit the file in this view.
If a solution does not contain a settings file, you can add it following these instructions: How to add a solution
settings file to a solution
Solution settings and test execution
The solution settings file ’Ranorex.rxsettings’ is automatically copied into the output directory of the test project. It
is saved in the same folder as the test executable. This is why the solution settings will be used for test execution.
Please note:
ˆ Do not rename the solution settings file.
ˆ When deploying the test executable, make sure to include the solution settings.
If the solution settings are not stored in the same folder as the test executable, the solution settings from the local
machine will be used.
Solution settings and Ranorex Remote
When selecting a solution for remote test execution, the solution settings saved in this solution will automatically be
sent to the Ranorex Agent and used during test execution.
If the solution does not include a solution settings file, the solution settings stored locally on the Ranorex Agent’s
machine will automatically be used during test execution.
242
Contents
Settings overview
General Settings
Figure 320: 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.
’Enable search by unique ID (if available)’
Specifies whether web elements should be identified using their unique id or not.
’On mouse/pointer move check if location is within visible desktop bounds’
Specifies whether an exception should be thrown if the mouse/pointer tries to move outside the visible desktop bounds
or not.
’Maximum length of text values in RanoreXPaths’
Specifies the maximum length of attribute values used within RanoreXPath.
243
Contents
’The factor that all timeouts 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.
’Restore all ignored technology specific limitation warnings’
Resets the ’Do not show again’ checkboxes used to suppress the assistance dialog for technology limitations. Click
’Restore Limitation Warnings’ to show the dialog again for not instrumented technologies or applications.
’Restore all ignored dialogs (”Do not show again”)’
Resets all other ’Do not show again’ checkboxes.
’GDI Capture Settings. . . ’
Opens the dialog to change the current GDI capture list. More information about the Ranorex GDI plug-In can be
found at Testing of Legacy Applications.
’Mobile Devices. . . ’
Opens the ’Manage Devices’ dialog as described in the sections ’iOS Testing’ and ’Android Testing’.
Note: Click 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.
Advanced Settings
244
Contents
Figure 321: Advanced Ranorex settings
Most of the settings shown in the ’Advanced’ tab 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.
’Use hidden screenshot capturing (if possible)’
Tries to capture screenshots used by recordings, repositories or Ranorex snapshot files, even from application windows
which are not in the foreground. If disabled, Ranorex tries to make the application window visible before capturing a
screenshot.
’Let snapshot contain complete ancestor subtree’
When checked, the subtree containing the whole application will be stored when saving a snapshot file. If not checked,
only the direct subtree to the selected item will be stored.
’Use asynchronous dispatching of mouse and keyboard events’
This setting is used to turn on or off asynchronous dispatching of mouse and keyboard events during recording. With
enabled asynchronous dispatching mouse and keyboard events will not be forwarded to an application before Ranorex
has finished processing the event.
245
Contents
’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. This improves performance is some cases.
’Use UiaLauncher to elevate privileges for processes started by tools’
Specifies whether test execution is started with elevated privileges or not.
’Synchronize element selection of Studio’s repository with element selection in Spy’
Specifies whether a UI element will be automatically selected in Ranorex Spy when the representing repository item
will be selected or not.
’Delay before pressing a key sequence (ms)’
Specifies the time to wait in milliseconds before performing a key sequence simulation.
’RanoreXPath generation mode:’
Defines how RanoreXPaths will be built during recording actions or tracking elements using the Ranorex tools (by
default, the mode ’StepCostReduce’ is selected).
StepCostReduce Reduces the number of path predicates such that the path remains non-ambiguous. In addition to
that, removes intermediate steps considered as unimportant. Can be heavily tuned using the RxPath.PathBuildMode
settings. This usually shortens the path and makes it more robust by eliminating unnecessary attributes.
Reduce Reduces the number of path predicates such that the path remains non-ambiguous. This usually shortens
the path and makes it more robust by eliminating unnecessary attributes.
Simple No optimization is performed. Path predicates contain valid, appropriate and existing attribute values or
indexes if no attributes can be used.
’Edit Path Weights. . . ’
In order to get assistance with editing RanoreXPath weights, have a look at the blog post Automated Testing and
Dynamic IDs. Please also have a look at our RanoreXPath Weight Rule Library for the latest RanoreXPath Weight
Rules.
’Edit Path Build Options’
Specifies the parameters for ’StepCostReduce’ RanoreXPath generation mode.
Recorder Settings
The description of the settings regarding the Ranorex Recorder can be found in the Recorder Settings Dialog in Lesson
5: Ranorex Recorder.
246
Contents
Repository Settings
The description of the settings regarding the Ranorex Repository can be found in the Repository Settings Dialog in
Lesson 6: UI Mapping with Ranorex Repository.
Imaging Settings
The Imaging settings are explained in the section Image-Based Automation in Lesson 5: Ranorex Recorder.
Plugin Specific Settings
Figure 322: Plugin specific user settings
247
Contents
Figure 323: Plugin specific solution settings
Plugin specific settings can be used to alter the behavior of individual Ranorex plugins, for example, to achieve
backwards compatibility with older versions.
CEF
Process name black list This list contains process names (without the file extension) which should be ignored by
the CEF plugin. If a process should be ignored by the CEF plugin, add it to the list in a new line.
Java
Enable filtering on the Fx scenegraph Filters dummy and intermediate containers out of the Fx scenegraph.
Show SWT custom data properties Includes SWT custom Widget Data values as dynamic properties.
Use Java SWT legacy automation mode Enable Java SWT legacy automation mode using MSAA and Win32
Whitelisted class names Adds additional whitelisted class names (comma separated) for java object recognition.
Mobile
Android OS Automation Enables automation on Android OS screens. Disable to increase performance.
248
Contents
Auto reconnect attempts When the connection to a device is lost Ranorex tries to reconnect automatically. With
this parameter you can specify how many reconnect attempts should be made until the device will be set to the ’Error’
state. If you don’t want to reconnect automatically, set this parameter to 0.
Connect timeout After this time span the connection attempt will be aborted if the device is not reachable.
Deploy timeout Sets the timeout for deploying an mobile app. The required time depends on your application
size and the deploy method. Deploying an app takes longer when deploying via network.
Devices This is used internally by the Ranorex system and is not user editable.
General timeout The timeout for short running background processes. This timeout is used for very short running
processes (less than 10 seconds in general). If you get a lot of timeout exceptions, that do not occur during special
operations like instrumentation or deploying, try to increase this value.
Group devices by Determines how devices are grouped in dialog.
Instrument timeout Sets the timeout for instrumentation operations. A good initial value is 2 minutes. For very
large applications the time required for instrumentation can take up to 10 minutes depending on the machine power.
iOS: Maximum number of invisible children -1 will fetch all cells of UITable and UICollection views. Use this
setting only, when all views have a relatively small number of cells and static/finite data sources. 0 will disable
fetching of invisible cells. Generally you should use this setting, when data in your tables is loaded dynamically e.g.
from successive web requests. # (e.g. 50) will fetch all visible cells and the first 50 cells surrounding the visible cells
area.
Java Runtime installation path. The path of the currently used Java Runtime Environment (JRE) installation
required for Android automation.
Network discovery timeout Specifies for how long Ranorex sends UDP broadcasts to find devices that can be
used for automation. Normally, a device should respond within a few seconds.
Prompt on IP - address change If set to true, Ranorex will try to check if the IP-address of a device has changed
since the last usage and will show a message if so. By setting this parameter to false you can disable this check.
Remote call timeout The time Ranorex waits for a remote procedure call response until it assumes a connection
loss if no response was received.
Screenshots on AndroidOS Captures screenshots on AndroidOS screens. Disable to improve test execution
performance.
Sort devices by Determines how devices are sorted in dialog.
USB discovery timeout The timeout for discovering USB connected devices.
249
Contents
MSAA
Evaluate computationally expensive attributes Setting this value to true will instruct the plugin to evaluate
attributes that are expensive to compute and may result in longer delays when getting such attributes. Note that
spying an element with such expensive attributes may then take considerable time.
Filter elements Setting this value to false will make all MSAA elements available without filtering, including
elements being unavailable, invisible, or equivalent to elements of other flavors.
Filter Windows Forms elements Setting this value to false will make MSAA elements available that are direct
children of Windows Forms elements and have the same role and screen rectangle as the parent element.
Filtering compatibility level If you need legacy RanoreXPaths (created with an older Ranorex version) to work
with the current Ranorex version, set this property to the appropriate value matching the Ranorex version used to
create the legacy RanoreXPaths.
Refine FromPoint results Setting this value to true results in an additional search operation for a better fitting
element for every MSAA FromPoint operation (e.g. used by Element.FindFromPoint). This may produce better
results if the MSAA FromPoint implementation of a control is broken.
Qt Enable filtering on the QtQuick scenegraph Enables filtering the QtQuick scenegraph by skipping or removing
unnecessary layout, loader and style items.
Use QT legacy automation mode Enable Qt legacy automation mode using MSAA and Qt Accessibility.
UIA
Enable debugging mode for Windows apps If set to true, the debugging mode for Windows apps will be enabled,
causing them to not be suspended until the logon session is closed (user logout). When set to false, the plugin will
instead try to resume suspended apps when it needs to access them (possible race condition may cause freeze until
app is manually resumed).
Enable filtering of Windows app frames If set to true, the frames of Windows apps introduced with Windows
10 are filtered and all relevant elements of those frames are displayed as child of the app element. This allows for
transparent automation of Windows apps in windowed and full-screen mode.
Enumerate lists using the ItemContainerPattern Setting this value to true instructs the plugin to use the
ItemContainerPattern to iterate items of virtual lists that implement this UI Automation pattern. Depending on the
implementation of the control, iterating children using this pattern should also return items that are currently scrolled
out of view, but might also be slower than the usual way to get child elements. Note that switching this setting can
render existing RanoreXPaths invalid for controls implementing the ItemContainerPattern.
Evaluate computationally expensive attributes Setting this value to true will instruct the plugin to evaluate
attributes that are expensive to compute and may result in longer delays when getting such attributes. Note that
spying an element with such expensive attributes may then take considerable time.
250
Contents
Force virtual items to be realized Forces virtual items to be realized when trying to get their child elements.
Setting this value to true will allow to search lists with virtual items, but realizing may have undesired effects on the
list depending on the list implementation, e.g. that the list is scrolled to make the realized item visible.
Provide elements for non-WPF windows natively implementing UIA Setting this value to true instructs the
plugin to provide elements also for non-WPF windows which natively implement the UIA interface.
Web
Enable automation of embedded IE web documents Enable automation of Internet Explorer web documents
embedded in other applications.
Win32
Enable accessibility (MSAA) actions and attributes Specifies whether Win32 elements provide accessibility
(MSAA) actions and attributes (as Dynamic capability).
Enable basic Delphi support Enables support for basic Delphi controls such as textboxes, buttons, etc. Set to
False for backwards compatibility.
Use legacy Form role Enables 2.X legacy mode where many elements improperly had the Form role. Set to True
for backwards compatibility with 2.X paths.
WPF
Note: With Ranorex 7.0 an Improved WPF plug-in was introduced.
Allow selected instance properties Extend the dynamic attribute list with entries for plain .NET properties. Each
line specifies a full-type name and the attribute name, separated by a pipe, like: Ranorex.ExampleType|IsAvailable
Disable WPF plug-in for processes Do not use the native WPF plug-in for any process specified in the list; keep
using UIAutomation for WPF as in Ranorex version up to 5.2.
Enable WpfDebug capability Enable the WpfDebug capability for all WPF elements. This capability provides
attributes and dynamic actions that are useful for analyzing issue in the element tree.
Ignore Attributes starting with Reduce clutter in the list of dynamic attributes.
Realize Items in Virtualizing Containers Many WPF containers only show children which are also visible on the
screen; to show all child-items, set this option to true. By default this is false, as the performance impact for large
grids can be very high.
Show All Elements Show the complete element tree, incorporating all visual and logical WPF elements. This
option disables any other filtering, and is useful for analyzing the structure of WPF applications when elements cannot
be accessed.
251
Contents
WPF Legacy/UIA Interaction Set to ’UiaOnly’ to completely deactivate this plug-in, making all other settings
obsolete. WpfOnly: Show only the native WPF plug-in tree, suppress UIA. WpfPreferred: Show both WPF and
UIA tree, and return WPF elements for tracking. UiaPreferred: Show both WPF and UIA tree, and return UIA
elements for tracking. UiaOnly: Do not use the native WPF plug-in at all, and keep using UIAutomation for WPF as
in Ranorex versions up to 5.2. WpfImprovedOnly: Show only the improved native WPF plug-in tree, suppress UIA.
WPF Tree
Always Show Visual Children Always show the visual children for specific types, even if those type do also have
one or more logical children. Enables accessing elements that are not part of the logical WPF element tree, like
data-binding generated elements for well-known types. Example: ”CurrentType|ParentType|ApparentParentType”
Each entry is a pipe (the |character) separated tuple of type-names for (current, parent, apparent-parent) elements.
An empty field denotes match-all, e.g. ”FrameworkElement||” matches for all parent and apparent-parent elements.
Never Show Visual Children Do not show the visual children for matching elements, even if those types do not have
any logical children. Reduces unnecessary element tree branched. Example: ”CurrentType|ParentType|ApparentParentType”
Each entry is a pipe (the |character) separated tuple of type-names for (current, parent, apparent-parent) elements.
An empty field denotes match-all, e.g. ”FrameworkElement||” matches for all parent and apparent-parent elements.
Skip Elements Neither show nor traverse elements for specific types. Reduces the size of the element tree by
hiding types not used in UI testing. Example: ”CurrentType|ParentType|ApparentParentType” Each entry is a pipe
(the |character) separated tuple of type-names for (current, parent, apparent-parent) elements. An empty field denotes
match-all, e.g. ”FrameworkElement||” matches for all parent and apparent-parent elements.
Skip Elements but Descend to Children Reduce the hierarchy levels by always hiding redundant elements, and
instead continuing the tree with its children. By default this skips over some common nested containers constructs.
Example: ”CurrentType|ParentType|ApparentParentType” Each entry is a pipe (the |character) separated tuple of typenames for (current, parent, apparent-parent) elements. An empty field denotes match-all, e.g. ”FrameworkElement||”
matches for all parent and apparent-parent elements.
Skip Elements but Descend to Single Child Reduce the hierarchy levels by hiding redundant containers, if they
have none or only one child element. By default this hides some layout-containers. Containers will be shown if they
contain at least two children. Example: ”CurrentType|ParentType|ApparentParentType” Each entry is a pipe (the
|character) separated tuple of type-names for (current, parent, apparent-parent) elements. An empty field denotes
match-all, e.g. ”FrameworkElement||” matches for all parent and apparent-parent elements.
252
Contents
Improved WPF plug-in
Ranorex 7.0 and the improved WPF plug-in
With Ranorex 7.0, weve introduced a new and improved WPF plug-in. It produces less complex element trees and
more logical RanoreXPaths, making your tests more reliable and robust. This is why we recommend you use the
improved WPF plug-in for all your new projects. It is the default setting for new solutions.
Your existing projects that use the WPF plug-in from previous Ranorex versions will still work in Ranorex 7.0.
Ranorex automatically activates the correct plug-in for you based on whether:
ˆ the solution contains any WPF elements,
ˆ any solution settings are present,
ˆ you performed a fresh installation of Ranorex 7.0 or upgraded from an existing installation.
This following table illustrates this. You can find a more detailed explanation of all the cases further below. Existing
solutionNew solutionwith solution settingswithout solution settings
Fresh installation
contains WPF elementsuse solution settings, no changescreate solution settings, use legacy plug-in with default
settingsn/adoesn’t contain WPF elementsuse solution settings and improved plug-inuse current local settings and
improved plug-inuse improved plug-in
Upgrade
contains WPF elementsuse solution settings, no changescreate solution settings, use legacy plug-in with previous
local settingsn/adoesn’t contain WPF elementsuse solution settings and improved plug-inuse current local settings
and improved plug-inuse improved plug-in
Local settings: User settings and Solution settingsstored on the local machine. Solution settings: Solution settings
stored in a solution. Legacy plug-in: The WPF plug-in for previous versions of Ranorex.
How to read the table: You performed a fresh installation of Ranorex 7.0. You are opening an existing solution that
contains WPF elements and solution settings: Ranorex will use the existing solution settings and make no changes.
Fresh installation
When you create a new solution, the improved plug-in is activated by default.
When you open an existing solution created in a previous version of Ranorex, its repositories are first scanned for
WPF elements:
WPF elements are found
ˆ There are solution settings: No changes are made. The existing solution settings apply.
ˆ There are no solution settings: Ranorex automatically generates the solution settings. The legacy WPF plug-in
for previous versions is activated with the default settings.
No WPF elements are found
ˆ There are solution settings: The improved WPF plug-in is activated, all other existing solution settings apply.
253
Contents
ˆ There are no solution settings: The improved WPF plug-in is activated and the current local settings are used.
Upgrade from an existing installation
If you upgraded from an existing installation, Ranorex 7.0 will use two separate local-settings files when determining
the correct WPF settings for you. The first file is the old local-settings file of your previous installation. For Ranorex
6, this file would be called RanorexConfig6.xml. The second file is created when you start Ranorex 7.0 for the first
time. It is a copy of the old local-settings file, renamed to RanorexConfig7.xml and configured to use the improved
WPF plug-in by default.
When you create a new solution, RanorexConfig7.xml is used and the improved WPF plug-in is activated by default.
When you open an existing solution created in a previous version of Ranorex, its repositories are first scanned for
WPF elements:
WPF elements are found
ˆ There are solution settings: No changes are made. The existing solution settings apply.
ˆ There are no solution settings: Ranorex automatically generates the solution settings. The legacy WPF plug-in
is activated and its settings from the old local-settings file (e.g. RanorexConfig6.xml) are applied to the solution
settings.
No WPF elements are found
ˆ There are solution settings: The improved WPF plug-in is activated, all other existing solution settings apply.
ˆ There are no solution settings: The improved WPF plugin is activated and the current local settings are used.
Attention - Ranorex standalone tools
In the standalone tools, (Ranorex Spy, Ranorex Recorder, etc.), the improved WPF plug-in is active by default. If you
are working with a solution that doesnt use the improved WPF plug-in, you must activate the correct WPF plug-in in
the standalone tool you want to use. Do not mix repository items created in different WPF-plug-in operation
modes. It will lead to conflicts. Follow these instructions to activate the correct WPF plug-in:
First, find out what WPF settings your solution is using:
1. With a solution open, click on Settings in the toolbar.
2. Click on the Plugins tab, select Solution Settings at the top, and then scroll down to the WPF section.
3. Find the option WPF Legacy/UIA Interaction and note what it is set to.
4. Keep the window open for reference.
Now activate the correct plug-in in the standalone tool you want to use:
1. Open the standalone tool you want to use.
2. Click on Settings, select Solution Settings at the top, and then scroll down to the WPF section.
3. Find the option WPF Legacy/UIA Interaction and select the same option from the drop-down menu as in the
window you kept open.
4. Click on OK in the bottom right of the window.
254
Contents
Selecting the WPF plug-in manually
You can also manually select the WPF plug-in you want to be activated for your solution in the solution settings.
To do so, follow these steps:
1. With a solution open, click on Settings in the toolbar.
2. Click on the Plugins tab, select Solution Settings at the top, and then scroll down to the WPF section.
3. Find the option WPF Legacy/UIA Interaction and select your desired option from the drop-down menu.
4. The other WPF settings will change accordingly. Please refer to the WPF section of the Settings overviewin
the User Guide for more information on what these settings do.
5. Click OK in the bottom right of the window.
255
Contents
Ranorex Remote
Ranorex Remote at a glance
Directly from Ranorex Studio, you can deploy your tests to remote machines for Execute tests with Ranorex Remote.
This enables you to execute your tests in parallel in different test environments such as different operating systems,
system configurations or versions of systems under test.
During remote test execution, the Remote Pad keeps you updated on the test performance, while you can continue
using your local machine. Once the test has been executed, youll receive a Run History that the report is ready.
Ranorex Remote uses Ranorex Agent, which can be Install and set up Ranorex Agent on either physical or virtual
machines in your network. Directly from Ranorex Studio, you can deploy tests for remote test execution to these
agents using the Remote Pad.
What to find where?
Everything related to the Ranorex Agent
ˆ Ranorex Agent
ˆ Install and set up Ranorex Agent
ˆ Configure Ranorex Agent
ˆ Remote System Requirements
ˆ Remote FAQ
Working in Ranorex Studio with Ranorex Remote
ˆ Remote Pad
ˆ Adding Ranorex Agents
ˆ Agent List
ˆ Execute tests
ˆ Run History
ˆ Remote Troubleshooting - what to do, when a Ranorex Agent can not be found?
ˆ Remote FAQ
256
Contents
Ranorex Agent
A Ranorex Agent is a standalone tool that enables remote test execution.
Quick facts:
ˆ A Ranorex Agent queues multiple requests and Execute tests one test at a time.
ˆ Agents can be Install and set up Ranorex Agent on physical and virtual machines.
ˆ One Ranorex Agent can be Install and set up Ranorex Agent per machine.
ˆ An active user session is required for a Ranorex Agent to run.
ˆ Remotely Execute tests tests are fully functional, including mouse and keyboard actions.
ˆ A Ranorex Runtime License is required for remote test Execute tests. When starting the agent, it is automatically
requested from the License Manager installed in the network. The license is released once the agent is shut
down.
When a Ranorex Agent is started, an icon will be shown in the Windows system tray. To open the Ranorex Agent
window, just click on this icon:
Figure 324
Using the context menu of this icon, you can open and close the agents window. Select ’Exit’ to shut down the
agent. Shutting down the agent will release the license, close the whole application. Running tests remotely will not
be possible after this action.
Figure 325
The window of the Ranorex Agent displays the agents job queue as well as the agent’s log, including technical details,
and the agent’s display name. The host name of the machine is shown in the title bar.
257
Contents
Figure 326
You can also configure the settings of an agent. For more information on this topic visit this section: Configure
Ranorex Agent
The Job Queue provides an overview of the currently executed and planned tests. The jobs are listed with their
individual Test Suite name and the issuer is presented with the machine’s name the issuing Ranorex Studio is running
on.
258
Contents
Figure 327
259
Contents
Install and set up Ranorex Agent
Complete these two steps to use a Ranorex Agent:
ˆ Install the Ranorex Agent
ˆ Setting up the Ranorex Agent
Install the Ranorex Agent
1. Download the installation package. Alternatively, you can click the ’Adding Ranorex Agents’ link in the Remote
Pad in Ranorex Studio.
2. Accept the terms in the License Agreement and press ’Install’
Figure 328
3. Wait for the Setup Wizard to finish installing the Ranorex Agent.
260
Contents
Figure 329
Note: Depending on your windows system configuration, you might need to give your consent in the Windows
User Account Control.
4. The installation has finished.
261
Contents
Figure 330
Check Start Ranorex Agent to automatically open the agent. The ’First Run Wizard’ will guide you through
the set up.
Setting up the Ranorex Agent
Complete the following steps to use a Ranorex Agent. When starting the Ranorex Agent for the first time, the ’First
Run Wizard’ will appear.
262
Contents
Figure 331
1. The display name will help you manage your Ranorex Agents in the Remote Pad of Ranorex Studio.
263
Contents
Figure 332
2. You need to install Ranorex Runtime to execute tests. You can decide to install Ranorex Runtime manually or
at a future point in time.
264
Contents
Figure 333
If you choose to install Ranorex Runtime at this point, it will immediately download and install automatically.
265
Contents
Figure 334
Please wait until the Ranorex Runtime installation is complete.
266
Contents
Figure 335
3. Configuration finished. Make sure the steps for preparing the agents host machine are completed.
267
Contents
Figure 336
The Ranorex Agent has been configured and the setup is finished. Press ’Next’ to open the main window of
the agent.
268
Contents
Configure Ranorex Agent
Ranorex Agent’s window with opened main menu is shown in the following picture:
Figure 337
In the top right corner of the agent’s window, open the main menu to:
ˆ Change Display Name The agent’s display name is shown in the top left corner of the agent’s window and in
the Remote Pad in Ranorex Studio. If you’ve changed the agent’s display name, all those, who have this agent
in their Agent List, will have to remove the agent with the former display name from their list, and re-add it
manually with the new display name.
ˆ Change License Manager Select to switch to another License Manager.
ˆ Show Files Opens the folder in the file system, which contains all data related to the agent.
ˆ Autostart at Logon Select to automatically start the Ranorex Agent after login into the machine.
ˆ Keep Session Active This setting makes sure that the user session keeps unlocked even if you close the remote
session. For more information also consult the How do I make sure that my user session keeps unlocked if I
close my remote session?.
Note: As this mechanism will keep your remote machine unlocked even if you’ve disconnected your RDP
session, an essential security mechanism is now disabled. Please beware that your remote machine can now
easily be accessed as the system security is disabled. We advise you to not store sensitive data on your remote
machine.
ˆ Always on Top Check this option to show the agent’s window on top of all other windows.
ˆ Exit Select to shut down the agent and release the license. In the Remote Pad in Ranorex Studio, this agent
will be displayed as not reachable.
269
Contents
Remote Pad
The Remote Pad is the central point of management to deploy tests to Ranorex Agents within Ranorex Studio.
This Remote Pad welcome screen will be shown after first installing Ranorex Studio or when your Agent List is empty.
To add an agent to your Agent List, press ’Add Ranorex Agent’ and follow the instructions.
270
Contents
Figure 338
271
Contents
Remote Pad is opened by default. In case it is closed just open the Remote Pad in Ranorex Studio by pressing the
’View Remote’ button in the toolbar section.
Figure 339
Once the Remote Pad is open, the ’View Remote’ button is disabled.
Figure 340
272
Contents
Adding Ranorex Agents
Please choose the task you want more details on:
ˆ Adding the first agent to your Agent List - Your Agent List is empty
ˆ Adding additional agents to your Agent List
ˆ Managing your Agent List
Adding the first agent to your Agent List
In case your Agent List is empty, the Remote Pad will show the Remote Welcome Screen.
273
Contents
Figure 341
274
Contents
To start adding a Ranorex Agent, press ’Add Ranorex Agent’.
Figure 342
In order to add a Ranorex Agent to your Agent List, an agent has to be installed on a machine in your network.
Start with step 1 to find a link to download the installation package. Find details on installing the Ranorex Agent
here: Install and set up Ranorex Agent
Once you’ve successfully installed a Ranorex Agent, or if you already have several agents running in your network,
please continue with step 2 to manage your Agent List. Follow this link to find out how to add an agent to your
Agent List: Managing your Agent List
275
Contents
Adding additional agents to your Agent List
In case you already have agents in your Agent List, please click on the icon in the top right corner of the Remote Pad
to manage your Agent List.
Figure 343
Follow this link to find out how to add an agent to your Agent List: Managing your Agent List
276
Contents
Agent List
The Agent List provides an overview of your agents, and enables you to manage agents and access the Run History.
The agents are listed with their display name, a status information and three controls.
Figure 344
Please find detailed information on how to execute remote tests in the section Execute tests. If you want to view your
remote test results, please refer to the section Run History.
Managing your Agent List
To add or remove agents from the Agent List, press the icon in the top right corner of the Remote Pad.
277
Contents
Figure 345
The ’Manage Agents’ view can come in two states:
ˆ Agent List is empty:
278
Contents
Figure 346
279
Contents
ˆ Agent List containing agents:
280
Contents
Figure 347
281
Contents
The section ’My Agents’ shows all agents currently contained in your Agent List. Use the ’Remove’ button to delete
agents from this list. Note that this action neither deletes the agent itself nor data on the agent, but merely removes
the agent from the list. You can always re-add a previously removed agent to your Agent List.
The section ’Available agents in your network’ lists all auto-discoverable agents in your network. To add an agent
to your Agent List, press ’Add Agent’.
In the last section of this list, you can manually search for agents within your network that are not auto-discoverable.
Enter the name or IP-address of the machine the agent is installed on, to find the desired agent.
Figure 348
If it cannot be found, please refer to the section Ranorex Agent in the user guide and make sure it has been correctly
Install and set up Ranorex Agent.
If an agent cannot be found even though it has been installed and configured, please make sure the System Requirements
for Ranorex Versions up to 6.0 are correct. If it still cannot be found, please consult the Remote Troubleshooting
section.
282
Contents
Execute tests
Press the run button next to an agent’s name to start executing the currently selected Run Configuration on this
Ranorex Agent.
Figure 349
To run a specific Run Configuration, open the ’Run’ button menu and select one of the items.
283
Contents
Figure 350
284
Contents
The test will be executed on the remote machine. You don’t have to wait for the test run to finish. Once you’ve
deployed your test to a remote machine, you can immediately continue using your local machine.
During remote test execution, you’ll receive information on the progress. By pressing the red stop button, you can
abort the remote test run.
Figure 351
Once the remote test has been executed successfully, you’ll receive a notification shown at the right most button
’Open Run History’. You’ll see a number of unread items in the Run History. If the circle is grey, it indicates that no
error has occurred since you’ve last accessed the Run History.
285
Contents
Figure 352
286
Contents
If there is at least one unread item in the Run History with an error state, the circle is shown in red.
Figure 353
An agent can queue several jobs. The number of items in the queue is shown in the grey circle on the ’Run’ button.
287
Contents
Figure 354
288
Contents
Run History
The Run History lists all finished runs of an agent. You can open the Run History with the right most button next to
each agent in your Agent List.
Figure 355
The Run History shows all tests that have been executed remotely in a descending order. By default, you’ll see all
test runs you’ve sent to the agent in the past 24 hours.
When selecting a test run, the actions that have been performed are shown in the details view below the list.
The list displays the result of the test run and the name of the test suite, including a timestamp of when the test
execution has finished. A check mark in a green circle indicates that the test has been executed successfully, whereas
a failed execution is highlighted with a white cross in a red circle.
289
Contents
Figure 356
290
Contents
Reports of remotely executed tests are stored on the machine of the agent they have been executed on. You have
three options to open a report: you can either double-click the desired test run, right-click the test run to open
its context menu and select ’Open Report’, or press the download button in the bottom right corner in the details
view. To save the report to your local machine or any other location, right-click on the opened report to get to the
context menu and select ’Save as’. If a test-run has failed, no report will be available.
The Run History provides three filter options: result, ownership and timespan. The ownership of a test run refers to
the name of the machine Ranorex Studio is running on.
Test runs can be deleted by all those who have access to the agent. Simply select the desired test run(s) and press the
delete key, or select ’Delete’ in the context menu for selected test run(s). When deleting a test run, all information
connected to this test run will be removed from the agent.
291
Contents
Remote System Requirements
A Ranorex Agent supports the same operating systems as Ranorex Studio and has the same software and hardware
requirements as the other Ranorex components. Please consult System Requirements section for more details. You
can find the specific firewall settings for Ranorex Agents here: Ranorex Agent Firewall Configuration.
292
Contents
Remote Troubleshooting
If the auto discovery or manual search for an agent have failed:
ˆ Make sure the Ranorex Agent is running in an active user session. Do not log off the user from the machine
the Ranorex Agent is running on.
ˆ Make sure the machine Ranorex Studio is running on, is in the same network (subnet) as the machine the
Ranorex Agent is running on.
ˆ Double-check the System Requirements for Ranorex Versions up to 6.0on the machine the Ranorex Agent is
running on.
ˆ Check the Windows Event Log on the machine the Ranorex Agent is running on for entries related to Ranorex
Agent.
293
Contents
Remote FAQ
These frequently asked questions regarding Ranorex Remote want to help you to find quick answers to important
topics. Just click on one of these questions to get to the answer.
ˆ Can I install a Ranorex Agent on a virtual machine?
ˆ Can I install more than one Ranorex Agent on the same machine?
ˆ Which type of licenses do I need for Ranorex Remote?
ˆ How many licenses do I need for remote test execution on a Ranorex Agent?
ˆ How do I deploy settings to a Ranorex Agent?
ˆ How do I make sure that my user session keeps unlocked if I close my remote session?
ˆ How to overcome NAT issues
Can I install a Ranorex Agent on a virtual machine?
Yes, a Ranorex Agent can be installed on virtual as well as on physical machines.
Can I install more than one Ranorex Agent on the same machine?
One Ranorex Agent can be installed in one operating system. If you want to run more than one Ranorex Agent on a
physical machine, you have to set up more operating systems on that machine.
Which type of licenses do I need for Ranorex Remote?
A Ranorex Agent uses one Ranorex Runtime license provided through a Ranorex License Manager.
How many licenses do I need for remote test execution on a Ranorex Agent?
The Ranorex Agent takes a Ranorex Runtime License at startup, and keeps it until the agent is shut down. The same
license is used for test execution. While the Ranorex Agent is running, one license is blocked - no matter if the agent
is idle (no tests executed) or tests are executed. Also the number of tests executed by the agent has no effect on the
number of licenses used.
How do I deploy settings to a Ranorex Agent?
Settings which were configured on your local machine, e.g. technology plugin settings, can be deployed to the remote
machine with the Ranorex Solution. Follow these steps to do so:
1. Open Windows Explorer and navigate to %appdata% on your local machine.
2. Copy file ’RanorexConfig6.xml’.
3. Open the file system directory of your Test Suite Project.
294
Contents
Figure 357
4. Paste ’RanorexConfig6.xml’ in this Folder.
5. Switch back to Ranorex Studio and enable showing all files in Projects View. The configuration file should be
visible in the list.
295
Contents
Figure 358
6. Include the configuration file to the project.
296
Contents
Figure 359
297
Contents
7. Open Properties pane for the file. Use the context menu or press F4 to do so.
8. Change property ’Copy to output directory’ to ’PreserveNewest’.
Figure 360
With this Setting, the configuration file will always be deployed to the Ranorex Agent.
If you change any setting after this procedure, you have to manually update the file in this project. Repeat steps 1 to
4 to do so.
How do I make sure that my user session keeps unlocked if I close my remote session?
Ranorex Remote requires an active user session to run tests on a remote machine. You can connect to a remote
machine using a remote desktop connection (RDP). As long as this remote connection is active, the remote machine
is unlocked and tests can be executed. If you disconnect the RDP session, your remote machine will be locked. As no
GUI is available in locked mode, your remote tests will fail.
Ranorex Agent shipped with Ranorex 6.0.1 and later includes the setting ’Keep Session Active’, which is enabled
by default. So no further steps are required. Find more information in section Configure Ranorex Agent.
To keep the remote session unlocked even if you’ve disconnected the RDP session in Ranorex 6.0, please follow
these instructions:
1. Create a batch file on your remote machine and insert the code below: for /f ”skip=1 tokens=3 usebackq”
%%s in ( ‘query user %username%‘ ) do ( %windir%\System32\tscon.exe %%s /dest:console )
2. Save this batch file on the desktop of your remote machine and name it: ’KeepSessionOpen.bat’.
3. If you need to disconnect the RDP session, you can now simply run this batch file using administrator privileges
and your remote machine will remain unlocked.
Note: As this mechanism will keep your remote machine unlocked even if you’ve disconnected your RDP
session, an essential security mechanism is now disabled. Please beware that your remote machine can now
easily be accessed as the system security is disabled. We advise you to not store sensitive data on your remote
machine.
298
Contents
How to overcome NAT issues
If the machine with the installed Ranorex Studio and the machine with the Ranorex Agent are connected to different
networks, this agent may not automatically appear in your Agent List and you may not be able to manually add it
using the IP address. By default, machines do not have the routing information to connect to a machine outside its
own network.
To overcome this issue, a network route has to be configured either on the gateways between the networks, or on
each machine.
Below, we’ve showcased an example in which Ranorex Studio and the Ranorex Agent are installed on machines which
are connected to different networks and have provided a solution on how to create a network route between them.
Figure 361
As you can see in the image above, our exemplary networks are starting with 192.168.x.x. One has the gateway
192.168.2.1, the other 192.168.3.1. Both gateways share the subnet 192.168.1.x. This subnet has the gateway
192.168.1.1., which is connected to the internet.
The network of gateway 192.168.3.1 contains two computers, one of which with three virtual machines (VMs) running
on it. All of them have 192.168.3.x IP addresses.
On the 192.168.2.1 network there is a router, and just two computers. All of these computers have 192.168.2.x IP
addresses.
If you ping ’192.168.2.2’ (PC 2) from computer ’192.168.3.6’ (VM C), then the request will time out, unless you
enable a proper route across the gateways. Assuming the 192.168.3.6 (VM C) is running Windows 7, type one of the
following commands on 192.168.3.6 (VM C):
ˆ route add 192.168.2.0 mask 255.255.255.0 192.168.1.2 metric 2 (add whole network to the route table) or
ˆ route add 192.168.2.2 mask 255.255.255.0 192.168.1.2 metric 2 (add single computer to the route table)
Once the command has been entered, the ping/communication would successfully go from 192.168.3.6 (VM C) to
299
Contents
192.168.2.2 (PC 2), but 192.168.2.2 (PC 2) would still not be able to ping 192.168.3.6 (VM C). There are two
workarounds to enable communication between these two networks:
ˆ Set up a route on the gateways
ˆ Set up the route on the machines that need to communicate across networks
Please consider the gateway firewalls when setting up the routes, as they may block cross-traffic from the machines.
If this is the case, you will need a network admin to either set up the route on the gateway instead or to set up port
forwarding to allow traffic through the firewall.
As most gateways behind corporate internet firewalls function as bridges, not much internal traffic is firewalled on the
local network. To check if your connection is firewalled, try ’tracert 192.168.2.2’. If stars ’*’ appear in the ’trace
route’ instead of IP addresses, then either the connection went through the firewall, or it has been misdirected into
the internet.
Please beware that a standard subnet has been chosen in this scenario: 255.255.255.0 Youll need to confirm the
subnet on either side of the gateways, and adjust your route setup commands as needed.
The route metric (last number in command) is assigned to a route and is used to identify its priority with 1 being
of the highest priority. Usually network admins base the router metric on the amount of hops in a route, as the route
with the least hops is usually the best. As the route in our example contains two hops, our router metric is 2.
Please note: A route command is only persistent (it will stay after reboot) if you add the -p argument to it. Thus,
you can easily try route commands at no risk beforehand, and simply reboot if youd like to make them undone. Once
youve found the right route, you can make the commands persistent after reboot.
300
Contents
User Code Library
The user code library is the central place where you can find user code collections and methods that have been
created within a test automation solution. This makes it easier to use and share user code methods within a solution
and across teams.
User code methods that logically belong together are organized in user code collections. You can add a description to
your user code collections and methods. These descriptions are shown in the user code library and help in selecting
the right user code method.
The library can be accessed directly from the action table. Simply select a desired method to directly use it as an
action.
The search functionality aids in finding a specific method in comprehensive user code libraries.
Find out how you can get the most out of the user code library:
For developers and testers with programming skills:
ˆ Collections and Methods
For testers:
ˆ Using the User Code Library
301
Contents
Collections and Methods
As a developer or tester with programming skills, you can create user code collections with user code methods, which
can then be shared within a solutions and teams.
All user code methods within a user code collection of a solution are instantly available in the user code library. You
can create multiple user code collections within a project.
Follow these steps to add a user code collection to a project:
1. Select the project in ’Projects’ view.
2. In the main menu, choose File > New > File, or Add > New Item in the context menu.
3. In the opened Dialog, choose ’User Code Collection’ and enter a suitable file name.
Figure 362
4. The code file is added to the project and opened. An empty class with the attribute ’[UserCodeCollection]’ is
automatically generated. Only classes with this attribute will be listed in the library.
302
Contents
Figure 363
Follow these steps to add a user code method to a user code collection:
1. Place the mouse cursor between the brackets of the class.
2. Open the context menu and click ’Insert New User Code Method’.
Figure 364
3. Fill in a suitable method name for the new user code method and press OK.
303
Contents
Figure 365
4. The stub for the new method is created. All user code methods have to be attributed with ’[UserCodeMethod]’
to be available in the user code library.
Figure 366
5. Write the code for the new method.
6. Update the summary to provide a suitable description. This description will be available in the library and helps
your colleagues in finding the method they are looking for.
304
Contents
Using the User Code Library
Where to find the user code library
You can directly access the user code library from the action table. Simply click ’Add New Action’ in the menu to
select a method from the library.
Figure 367
How does the user code library look like?
All collections and their methods within a test automation solution are available in the user code library and displayed
in aphabetical order.
305
Contents
Figure 368
When you select a collection or method, its description is automatically displayed.
You are looking for a specific collection or method? Then you can use the search and filter functionality above the
list. The keyword you enter will be used to filter the library content for method names, namespaces and descriptions.
Add a user code method from user code library
1. Choose a user code method from the list.
306
Contents
Figure 369
2. Confirm your selection by pressing the button ”Confirm Selection”. The selected user code method will be
added as action to the recording.
307
Contents
Figure 370
308
Contents
Endpoints
Endpoints are the gateways through which a locally executed test exchanges data with an external AUT. In simpler
words, they allow you to test an external application or system as if it were on your machine.
The endpoint pad allows you to view and add endpoints. Open the pad by clicking on ”View Endpoints” in the
toolbar.
Figure 371
Adding your first endpoint
If you havent added any endpoints yet, the welcome screen will be shown.
309
Contents
Figure 372
310
Contents
Click on ”Add endpoint” to continue and follow the instructions for adding an Android, iOS, or WebDriver endpoint.
Adding additional endpoints
If youve added an endpoint before, the Endpoint list will appear and the pad will look like this:
Figure 373
Click on the ”+” sign to continue and follow the instructions for adding an Adding Android endpoint, Adding iOS
endpoint, or Adding WebDriver endpointendpoint.
Shortcuts and command line execution
When building a solution, shortcut files for each endpoint are created in the output folder where the test executable is
saved as well. These shortcuts allow you to execute the test directly on a specific endpoint.
311
Contents
Figure 374
You can also do this by using the Running Tests via Command Line ”endpoint”.
312
Contents
Endpoint list
The endpoint list shows the desktop computer you are running Ranorex Studio on and all endpoints added. The
endpoints are categorized according to their type (Android, iOS, WebDriver) and displayed with their name, address,
and connection status (Connected, Offline, Error). You can search the listed endpoints by name using the search bar
at the top.
Figure 375
Set as automation root
Click the icon to the left of an endpoint to activate it as automation root. The run buttons in the Ranorex Studio
toolbar and the test suite toolbar will change accordingly. Once an endpoint has been activated, tests can only
interact with this endpoint and will receive and send all data for test execution through this endpoint.
313
Contents
Figure 376
The endpoint is not the automation root. Click it to set the endpoint as automation root.
Figure 377
The endpoint is the automation root.
Figure 378
Run button in the Ranorex Studio toolbar when a mobile device or WebDriver endpoint is set as automation root.
314
Contents
Figure 379
Run button in the test suite toolbar when a mobile device or WebDriver endpoint is set as automation root.
Endpoint options
Click the icon to the right of an endpoint to display a set of options for it. The available options change depending
on the endpoint type.
Set as automation root: Does the same as clicking the icon to the left of an endpoint (see above).
View Details: Displays a detailed view of the endpoints properties. For Android or iOS endpoints, you will also see a
list of the instrumented apps on the device. Click on the icon to the right of an app to start the instrumented app on
the device. Click on the rocket button at the bottom to instrument and deploy an app on the device. For further
information, please refer to the Android and iOS instrumentation chapters of the user guide.
Instrument and deploy app*: Allows you to instrument and deploy an app on the device. For further information,
please refer to the Android and iOS instrumentation chapters of the user guide.
Save ADB log**: Allows you to save the log file of the ADB (Android debug bridge).
Refresh*: Refreshes the connection to the endpoint.
Delete: Deletes the endpoint form the endpoint list.
* only available for Android and iOS endpoints ** only available for Android endpoints
315
Contents
Figure 380: Endpoint options for desktop
316
Contents
Figure 381: Endpoint options for Android endpoints
317
Contents
Figure 382: Endpoint options for iOS endpoints
318
Contents
Figure 383: Endpoint options for WebDriver endpoints
319
Contents
Adding Android endpoint
1. Open the endpoint pad.
2. If you haven’t added an endpoint yet, click on ”Add endpoint” to continue. If you have added an endpoint
before, click on the ”+” sign to continue.
3. Select Android from the list in step 1.
4. You will now need to prepare your device so it can be added as an endpoint. First, install the RxService
App on the device. You can do so by scanning the QR code or by downloading the required files from
ranorex.com/RxApp. Then connect your device to the same network as the computer you are running Ranorex
Studio on. Alternatively, you can also connect it directly to the computer via USB. Finally, start the RxService
App on your device.
5. Your device should now appear in the list at the bottom. Select it. If you want to change the name of the
device as it will appear in the Endpoint list, click on ”Other Device” and enter a new name in the ”Endpoint
name” field. Do not change the IP address or device serial (USB).
6. Finally, click on ”Add endpoint”.
320
Contents
Figure 384
321
Contents
Note: If your device is missing from the list, try clicking the refresh button. You can also add a device
manually by clicking on ”Other Device”. Choose an endpoint name and enter the devices IP address or USB
serial. Click on ”Add endpoint”.
You have successfully added the device. It will now appear in the endpoint list. Click on ”Add endpoint” to add
another device or on ”Complete setup” to return to the endpoint list.
322
Contents
Adding iOS endpoint
1. Open the endpoint pad.
2. If you haven’t added an endpoint yet, click on ”Add endpoint” to continue. If you have added an endpoint
before, click on the ”+” sign to continue.
3. Select iOS from the list in step 1.
4. You will now need to prepare your device so it can be added as an endpoint. First, install the RxService
App on the device. You can do so by scanning the QR code or by downloading the required files from
ranorex.com/RxApp. Then connect your device to the same network as the computer you are running Ranorex
Studio on. Alternatively, you can also connect it directly to the computer via USB. Finally, start the RxService
App on your device.
5. Your device should now appear in the list at the bottom. Select it. If you want to change the name of the
device as it will appear in the Endpoint list, click on ”Other Device” and enter a new name in the ”Endpoint
name” field. Do not change the IP address or device serial (USB).
6. Finally, click on ”Add endpoint”.
323
Contents
Figure 385
324
Contents
Note: If your device is missing from the list, try clicking the refresh button. You can also add a device
manually by clicking on ”Other Device”. Choose an endpoint name and enter the devices IP address or USB
serial. Click on ”Add endpoint”.
You have successfully added the device. It will now appear in the endpoint list. Click on ”Add endpoint” to add
another device or on ”Complete setup” to return to the endpoint list.
325
Contents
Adding WebDriver endpoint
1. Open the endpoint pad.
2. If you haven’t added an endpoint yet, click on ”Add endpoint” to continue. If you have added an endpoint
before, click on the ”+” sign to continue.
3. Select WebDriver from the list in step 1.
4. Choose a name for the Selenium Server you want to add and enter its URL or IP address.
5. Click on ”Test connection” to check whether the Selenium Server can be connected to. If this fails, make sure
youve entered the endpoint address correctly and that the endpoint is connected to an accessible network or
the Internet.
6. Finally, click on ”Add endpoint”.
326
Contents
Figure 386
327
Contents
You have successfully added the WebDriver endpoint. It will now appear in the endpoint list. Click on ”Add endpoint”
to add another device or on ”Complete setup” to return to the endpoint list.
328
Contents
Selenium WebDriver integration
With the Selenium WebDriver integration, you can run web tests created with Ranorex on different browsers, operating
systems, and machines without any plug-ins or add-ons.
Ranorex uses the existing Selenium WebDriver infrastructure torun web tests on:
ˆ Microsoft Edge, Google Chrome, Mozilla Firefox, and Chromium on Microsoft Windows
ˆ Apple Safari, Google Chrome, and Mozilla Firefox on Apple macOS
ˆ Google Chrome and Mozilla Firefox on Linux
Note: Web tests still have to be recorded locally. You will need Ranorex Studio, a locally installed web
browser with activated Ranorex automation add-on, and your local computer has to be set as automation
root in the Endpoint list. Ranorex Studio supports the following OS + browser combinations for web-test
recording: Microsoft Windows + Microsoft Internet Explorer, Google Chrome, Mozilla Firefox, and Chromium.
Quick-start guide for Selenium WebDriver integration in Ranorex
1. Setting up a Selenium WebDriver infrastructurea Selenium WebDriver infrastructure.
2. Running Selenium ServerSelenium Standalone Server.
3. Adding WebDriver endpoint to Ranorex Studio.
4. Record your web test on your local machine or use an existing one.
5. Review the web test following these Web test guidelines.
6. Set the WebDriver endpoint as Endpoint list.
7. Run the test Suite.
Setting up a Selenium WebDriver infrastructure
This chapter only provides a basic introduction. For complete documentation of the Selenium WebDriver infrastructure,
please visit the official Selenium web site.
For a basic setup, you will need:
ˆ The Java Runtime Environment
ˆ A Selenium Server Download the latest version of Selenium Standalone Server and place it into a folder.
ˆ Drivers for the web browser you want Selenium Server to automate All related links and setup steps can be
found here. Download the correct driver for your platform, unpack if needed, and place into the same folder as
Selenium Standalone Server.
329
Contents
Running Selenium Server
Before adding an endpoint or running a test you need to start the server.
Open a command line console and switch to the folder containing Selenium Standalone Server. Execute the following
command: java -jar selenium-server-standalone-.jar
Replace ”” with the version number of the downloaded Selenium Standalone Server file. The
window has to remain open.
Web test guidelines
Selenium WebDriver differs from the web testing capabilities that Ranorex offers for desktop-based web tests. After
recording a web test on your local web browser, follow these steps to make it compatible for execution with Selenium
WebDriver:
ˆ Remove all actions and repository items which interact with the web browser application itself.
ˆ Use the Close Application action for closing the web browser.
ˆ Please also refer to the Ranorex 7.0 release notes. They contain important information about the Selenium
WebDriver integration.
330
Contents
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 Code
ˆ Wait for UI Elements Using Repository
ˆ Create Adapters to Access More Properties and Methods
ˆ Create a List of Adapters From a Repository Element
ˆ Using Validate Class
ˆ Forcing a Test Case to Fail Using the Validate Class
ˆ Forcing a Test Case to Fail using Exceptions
ˆ Set Up Automation Speed
ˆ Accessing Test Case & Test Suite Context
ˆ Advanced Code Examples
ˆ How to do image based automation
ˆ How to find and compare images
ˆ Handling unexpected Dialogs
ˆ Advanced Validation - Clipboard
ˆ Advanced Validation - Whole Table
ˆ Advanced Validation - Whole Table in Web
ˆ Advanced Validation - File (text-based)
ˆ Advanced Validation - File (non text-based, binary)
ˆ Advanced Validation - Database (Single Field)
ˆ Advanced Validation - Database (Whole Table)
ˆ Advanced Validation - XML code
Using Repository in Code
C#
[TestModule("D451F1D1 -C347 -4B58 -939F-F6187642EB56", ModuleType.UserCode , 1)]
public class UsingRepository : ITestModule
{
// Repository object to access UI elements
MyFirstTestProjectRepository repo = MyFirstTestProjectRepository.Instance;
///
/// Constructs a new instance.
///

public UsingRepository ()
{
// Do not delete - a parameterless constructor is required!
}
void ITestModule.Run()
331
Contents
{
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();
// 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 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
Public Class UsingRepository
Implements ITestModule
’ Repository object to access UI elements
Private repo As MyFirstTestProjectRepository = MyFirstTestProjectRepository.Instance
’’’
’’’ Constructs a new instance.
’’’

’ Do not delete - a parameterless constructor is required!
Public Sub New()
End Sub
’’’
’’’ Performs the playback of actions in this module.
’’’

’’’ You should not call this method directly , instead pass the module
’’’ instance to the method
’’’ that will in turn invoke this method.

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
332
Contents
’ 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()
’ 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 ’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#
// 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 existence of the repository item ,
// but does not throw any exception
Validate.Exists(repo.SaveDialog.ButtonOKInfo ,"Check Object ’{0}’",false);
333
Contents
VB.NET
’ 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 ’
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 existence 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 Ranorex Spy, you see that that the application window provides
three adapters (Form, Control and NativeWindow). The Ranorex.Form adapter with all attributes and methods is
directly available using the repository’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
Control. As you can see in the code section below the ’. . . Info’ object is used to create the desired adapter.
C#
// Creating adapter of type ’NativeWindow ’ using the "\dots Info" object
Ranorex.NativeWindow nativeWnd = repo.MyApp.SelfInfo.CreateAdapter ( false
);
// \dots 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 ( 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
’ Creating adapter of type ’NativeWindow ’ using the "\dots Info" object
Dim nativeWnd As Ranorex.NativeWindow = repo.MyApp.SelfInfo.CreateAdapter(Of Ranorex.
NativeWindow)(False)
’ \dots 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 ’
334
Contents
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 CreateAdapters method to create a list
of adapters.
C#
// Create a list of adapters using the "Info" object
IList buttonList =
repo.MyApp.EnabledButtonsInfo.CreateAdapters ();
// 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
’ 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: Repository Items Representing
Multiple Elements
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
success messages to the report.
C#
335
Contents
// 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 existence of the repository item ,
// 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
’ 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 existence of the repository item ,
’ but does not throw any exception
Dim exists 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 documentation.
Forcing a Test Case to Fail Using the Validate Class
As described above you can use the Validate class to compare values from UI and non UI related objects bringing a
test to fail or success. Additional to this, you can force a test case to fail without comparing using the Validate class.
C#
Ranorex.Cell cellObject = null;
// Try to find a cell object
bool found=false;
found = Host.Local.TryFindSingle ("/form//table/row/cell [3]", 2000, out
cellObject);
// If the expressions does not return an object
// call Validate.Fail and the test case fails
if (!found) Validate.Fail("RanoreXPath with no return");
336
Contents
VB.NET
Dim cellObject As Ranorex.Cell = Nothing
’ Try to find a cell object
Dim found As Boolean = False
found = Host.Local.TryFindSingle(Of Ranorex.Cell)("/form//table/row/cell [3]", 2000, cellObject
)
’ If the expressions does not return an object
’ call Validate.Fail and the test case fails
If Not found Then
Validate.Fail("RanoreXPath with no return")
End If
Forcing a Test Case to Fail using Exceptions
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 successful. 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#
Ranorex.Cell cellObject = null;
// Try to find a cell object using two
// different RanoreXPath expressions
bool found=false;
found = Host.Local.TryFindSingle ("/form//table/row/cell [3]", 2000, out
cellObject);
found = found \textpipe \textpipe Host.Local.TryFindSingle ("/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)
{
throw new Ranorex.ElementNotFoundException("Both RanoreXPath with no return", null);
}
else
{
// If the value of attribute ’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
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 = found OrElse Host.Local.TryFindSingle(Of Ranorex.Cell)("/form// table/row/cell [4]",
2000, cellObject)
337
Contents
’ 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 attribute ’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#
void ITestModule.Run()
{
Mouse.DefaultMoveTime = 300;
Keyboard.DefaultKeyPressTime = 100;
Delay.SpeedFactor = 1.0;
}
VB.NET
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 module variables varDialogTextA (Code
Module A) and varDialogTextB (Code Module B) which are both bound to a parameter specified within the test
case’s data binding dialog to transfer data within a test case.
C#
// ----------------- 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 the variable ’varDialogTextA ’ bound to a test case parameter
varDialogTextA = repo.SaveDialog.TextMessage.TextValue;
// -------- Code Block used by User Code Action of recording B -------338
Contents
// Read value of module variable ’varDialogTextB ’ in other code module
// or recording module using a user code action
Report.Info(varDialogTextB);
// Get the current data context and log
// the current row index of a data driven run
Report.Info(TestCase.Current.DataContext.CurrentRowIndex.ToString ());
VB.NET
’ ----------------- 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 the variable ’varDialogTextA ’ bound to a test case parameter
varDialogTextA = repo.SaveDialog.TextMessage.TextValue
’ -------- Code Block used by User Code Action of recording B -------’ Read value of module variable ’varDialogTextB ’ in other code module
’ or recording module using a user code action
Report.Info(varDialogTextB)
’ Get the current data context and log
’ the current row index of a data driven run
Report.Info(TestCase.Current.DataContext.CurrentRowIndex.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#
// 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 ("/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 ("/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 buttonList = Host.Local.Find ("/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 ("button[@controlname=’btAdd
’]" ,2000);
VB.NET
339
Contents
’ 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)
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 ’Click’ method.
C#
// 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
’ 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).
340
Contents
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 ’Contains’ method.
C#
// 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
’ 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
A common problem in UI testing is the appearance of an unexpected dialog - e.g. the Update-Check dialog in KeePass.
341
Contents
Figure 387: Update-Check dialog
To overcome this issue, you can use the PopupWatcher class.
Using this class you can add watches for each dialog which might pop up during test execution.
In this watches you can specify a RanoreXPath or a Repository item the PopupWatcher should keep watching for, as
well as a method which should be triggered or a repository item which should be clicked.
C#
void ITestModule.Run()
{
// Create PopupWatcher
PopupWatcher myPopupWatcher = new PopupWatcher ();
// Add a Watch using a RanoreXPath and triggering the Method CloseUpdateCheckDialog
myPopupWatcher.Watch("/form[@controlname=’UpdateCheckForm ’]/ button[@controlname=’m_btnClose ’]
", CloseUpdateCheckDialog);
// Add a Watch using the info object of a button and triggering the Method
CloseUpdateCheckDialog
// myPopupWatcher.Watch(repo.UpdateCheckDialog.btCloseInfo , CloseUpdateCheckDialog);
// Add a Watch using the info object of the dialog and the info object of the button to click
// myPopupWatcher.WatchAndClick(repo.UpdateCheckDialog.SelfInfo , repo.UpdateCheckDialog.
btCloseInfo);
// Add a Watch using a repository folder object and the info object of the button to click
// myPopupWatcher.WatchAndClick(repo.UpdateCheckDialog , repo.UpdateCheckDialog.btCloseInfo);
// Start PopupWatcher
myPopupWatcher.Start();
}
public static void CloseUpdateCheckDialog(Ranorex.Core.Repository.RepoItemInfo myInfo , Ranorex
.Core.Element myElement)
{
myElement.As().Click();
}
public static void CloseUpdateCheckDialog(Ranorex.Core.RxPath myPath , Ranorex.Core.Element
myElement)
{
myElement.As().Click();
}
VB.NET
342
Contents
Private Sub ITestModule_Run () Implements ITestModule.Run
’ Create PopupWatcher
Dim myPopupWatcher As New PopupWatcher ()
’ Add a Watch using a RanoreXPath and triggering the Method CloseUpdateCheckDialog
myPopupWatcher.Watch("/form[@controlname=’UpdateCheckForm ’]/ button[@controlname=’
m_btnClose ’]", AddressOf CloseUpdateCheckDialog)
’ Add a Watch using the info object of a button and triggering the Method
CloseUpdateCheckDialog
’ myPopupWatcher.Watch(repo.UpdateCheckDialog.btCloseInfo , CloseUpdateCheckDialog);
’ Add a Watch using the info object of the dialog and the info object of the button to
click
’ myPopupWatcher.WatchAndClick(repo.UpdateCheckDialog.SelfInfo , repo.UpdateCheckDialog
.btCloseInfo);
’ Add a Watch using a repository folder object and the info object of the button to
click
’ myPopupWatcher.WatchAndClick(repo.UpdateCheckDialog , repo.UpdateCheckDialog.
btCloseInfo);
’ Start PopupWatcher
myPopupWatcher.Start()
End Sub
Public Shared Sub CloseUpdateCheckDialog(myInfo As Ranorex.Core.Repository.RepoItemInfo ,
myElement As Ranorex.Core.Element)
myElement .[As](Of Ranorex.Button)().Click()
End Sub
Public Shared Sub CloseUpdateCheckDialog(myPath As Ranorex.Core.RxPath , myElement As Ranorex.
Core.Element)
myElement .[As](Of Ranorex.Button)().Click()
End Sub
Advanced Validation - Clipboard
This sample shows how the current content of the clipboard can be validated against a given reference value.
C#
public void Validate_ClipboardContentEqual(string compareText , string customLogMessage)
{
// check if content of clipboard is text
if (System.Windows.Forms.Clipboard.ContainsText ())
{
// Get text from clipboard
string clipboardtext = System.Windows.Forms.Clipboard.GetText ();
// prepare log message if the log -parameter is empty
if (string.IsNullOrEmpty(clipboardtext))
{
customLogMessage = "Comparing content of clipboard with given text:
({0} vs. {1})"; ;
}
// Validate if given text (compareText) is equal to current text in clipboard
Ranorex.Validate.AreEqual(clipboardtext , compareText , customLogMessage);
}
else
{
throw new Ranorex.RanorexException("There is not text on the clipboard that
can be compared");
}
}
VB.NET
Public Sub Validate_ClipboardContentEqual(compareText As String , customLogMessage As String)
’ check if content of clipboard is text
343
Contents
If System.Windows.Forms.Clipboard.ContainsText () Then
’ Get text from clipboard
Dim clipboardtext As String = System.Windows.Forms.Clipboard.GetText ()
’ prepare log message if the log -parameter is empty
If String.IsNullOrEmpty(clipboardtext) Then
customLogMessage = "Comparing content of clipboard with given text:
({0} vs. {1})"
End If
’ Validate if given text (compareText) is equal to current text in clipboard
Ranorex.Validate.AreEqual(clipboardtext , compareText , customLogMessage)
Else
Throw New Ranorex.RanorexException("There is not text on the clipboard that
can be compared")
End If
End Sub
Advanced Validation - Whole Table
This sample shows how the content of a whole table (UI control) can be validated at once. Therefore the table has to
be passed as a parameter. Additionally the filename of a Ranorex Snapshot needs to be provided which will act as a
reference and defines the expected content of the table.
Note: The referencing snapshot has to be created before calling this advanced validation function. Simply select
the table in the tree view in Ranorex Spy, right-click and choose ”Save as Snapshot” in the context menu. More
information on creating snapshots can be found here: Creating Ranorex Snapshot Files.
C#
public void Validate_TableContentEqual(Ranorex.Adapter repoItem , string
filename_ReferenceTableSnapshot , string customLogMessageOverall , string
customLogMessageDetail)
{
// check if snapshot file exists
const string fileNotExists = "The given file does not exist: {0}";
if (! System.IO.File.Exists(filename_ReferenceTableSnapshot))
{
throw new Ranorex.ValidationException(string.Format(fileNotExists ,
filename_ReferenceTableSnapshot));
}
ElementSnapshot snap = null;
try
{
snap = Ranorex.Core.ElementSnapshot.CreateFromFile (
filename_ReferenceTableSnapshot); // ElementSnapshot.CreateFromFile is
available starting with Ranorex 5.4.2
}
catch
{
throw new Ranorex.ValidationException("Snapshot could not be loaded from file"
);
}
// restore table from snapshot
Ranorex.Table refTable;
try
{
refTable = snap.Element;
}
catch
{
throw new Ranorex.ValidationException("Table could not be created from
snapshot");
}
var tableAdapter = repoItem.As ();
if (tableAdapter ==null)
{
344
Contents
throw new Ranorex.ValidationException("Repo -item could not be accessed");
}
// check if rowcount is identical
if (tableAdapter.Rows.Count != refTable.Rows.Count)
{
throw new Ranorex.ValidationException(String.Format ("Tables do not have same
number of rows ({0} vs. {1})", tableAdapter.Rows.Count , refTable.Rows.
Count));
}
// run through table -rows
for (int iRow = 0; iRow <= tableAdapter.Rows.Count - 1; iRow ++)
{
int cellCountCur = tableAdapter.Rows[iRow].Cells.Count;
int cellCountRef = refTable.Rows[iRow].Cells.Count;
// check if number of cells is identical in current row
if (cellCountCur != cellCountRef)
{
throw new Ranorex.ValidationException(String.Format("Table -Rows do not
have same number of cells ({0} vs. {1})", cellCountCur ,
cellCountRef));
}
// run through cells in current row
for (int iCol = 0; iCol <= cellCountCur - 1; iCol ++)
{
string aCurText = tableAdapter.Rows[iRow].Cells[iCol].As >().Text;
string aRefText = refTable.Rows[iRow]. Cells[iCol].As().
Text;
string validationMessage = string.Empty;
if (string.IsNullOrEmpty(customLogMessageDetail))
{
validationMessage = String.Format ("Comparing content of cell
({2}/{3}) (found:’{0}’, expected: ’{1}’)", aCurText ,
aRefText , iRow ,iCol);
}
else
{
validationMessage = customLogMessageDetail;
}
// validate whether current text and expected text are identical
Ranorex.Validate.AreEqual (aCurText , aRefText , validationMessage);
}
}
// Log overall success
if (string.IsNullOrEmpty(customLogMessageOverall))
customLogMessageOverall = "Successfully completed content -validation of table
with provided snapshot of table (reference)";
Ranorex.Report.Log (ReportLevel.Success , customLogMessageOverall);
}
VB.NET
public Sub Validate_TableContentEqual(repoItem As Ranorex.Adapter ,
filename_ReferenceTableSnapshot As String , customLogMessageOverall As String ,
customLogMessageDetail As String)
’ check if snapshot file exists
Const fileNotExists As String = "The given file does not exist: {0}"
If Not System.IO.File.Exists(filename_ReferenceTableSnapshot) Then
Throw New Ranorex.ValidationException(String.Format(fileNotExists ,
filename_ReferenceTableSnapshot))
End If
Dim snap As ElementSnapshot = Nothing
Try
snap = Ranorex.Core.ElementSnapshot.CreateFromFile(
filename_ReferenceTableSnapshot) ’ElementSnapshot.CreateFromFile is
available starting with Ranorex 5.4.2
Catch
Throw New Ranorex.ValidationException("Snapshot could not be loaded from file"
)
345
Contents
End Try
’ restore table from snapshot
Dim refTable As Ranorex.Table
Try
refTable = snap.Element
Catch
Throw New Ranorex.ValidationException("Table could not be created from
snapshot")
End Try
Dim tableAdapter = repoItem .[As](Of Ranorex.Table)()
If tableAdapter Is Nothing Then
Throw New Ranorex.ValidationException("Repo -item could not be accessed")
End If
’ check if rowcount is identical
If tableAdapter.Rows.Count <> refTable.Rows.Count Then
Throw New Ranorex.ValidationException ([ String ]. Format("Tables do not have same
number of rows ({0} vs. {1})", tableAdapter.Rows.Count , refTable.Rows.
Count))
End If
’ run through table -rows
For iRow As Integer = 0 To tableAdapter.Rows.Count - 1
Dim cellCountCur As Integer = tableAdapter.Rows(iRow).Cells.Count
Dim cellCountRef As Integer = refTable.Rows(iRow).Cells.Count
’ check if number of cells is identical in current row
If cellCountCur <> cellCountRef Then
Throw New Ranorex.ValidationException ([ String ]. Format("Table -Rows do
not have same number of cells ({0} vs. {1})", cellCountCur ,
cellCountRef))
End If
’ run through cells in current row
For iCol As Integer = 0 To cellCountCur - 1
Dim aCurText As String = tableAdapter.Rows(iRow).Cells(iCol).[As](Of
Ranorex.Cell)().Text
Dim aRefText As String = refTable.Rows(iRow).Cells(iCol).[As](Of
Ranorex.Cell)().Text
Dim validationMessage As String = String.Empty
If String.IsNullOrEmpty(customLogMessageDetail) Then
validationMessage = [String ]. Format("Comparing content of cell
({2}/{3}) (found:’{0}’, expected: ’{1}’)", aCurText ,
aRefText , iRow , iCol)
Else
validationMessage = customLogMessageDetail
End If
’ validate whether current text and expected text are identical
Ranorex.Validate.AreEqual(aCurText , aRefText , validationMessage)
Next
Next
’ Log overall success
If String.IsNullOrEmpty(customLogMessageOverall) Then
customLogMessageOverall = "Successfully completed content -validation of table
with provided snapshot of table (reference)"
End If
Ranorex.Report.Log(ReportLevel.Success , customLogMessageOverall)
End Sub
Advanced Validation - Whole Table in Web
This sample shows how the content of a whole web table (HTML tag table) can be validated at once. Therefore the
table has to be passed as a parameter. Additionally the filename of a Ranorex Snapshot needs to be provided which
will act as a reference and defines the expected content of the web table.
Note: The referencing snapshot has to be created before calling this advanced validation function. Simply select
the table in the tree view in Ranorex Spy, right-click and choose ”Save as Snapshot” in the context menu. More
information on creating snapshots can be found here: Creating Ranorex Snapshot Files.
346
Contents
C#
public void Validate_WebTableContentEqual(Ranorex.Adapter repoItem , string
filename_ReferenceTableSnapshot , string customLogMessageOverall , string
customLogMessageDetail)
{
// check if snapshot file exists
Ranorex.Validate.IsTrue (System.IO.File.Exists (filename_ReferenceTableSnapshot),
string.Format("Checking existence of snapshot file: {0}",
filename_ReferenceTableSnapshot ));
ElementSnapshot snap;
try
{
snap = Ranorex.Core.ElementSnapshot.CreateFromFile (
filename_ReferenceTableSnapshot); // ElementSnapshot.CreateFromFile is
available starting with Ranorex 5.4.2
}
catch
{
throw new Ranorex.ValidationException ("Snapshot could not be loaded from file
");
}
// restore table from snapshot
Ranorex.TableTag refTable;
try
{
refTable = snap.Element;
}
catch (Exception e)
{
throw new Ranorex.ValidationException("Table could not be created from snapshot.", e)
;
}
Ranorex.TableTag tableAdapter = repoItem.As ();
if (tableAdapter ==null)
{
throw new Ranorex.ValidationException("Repo -item could not be accessed.");
}
IList actTableRows = tableAdapter.FindDescendants ();
int rowCntAct = actTableRows.Count;
IList refTableRows = refTable.FindDescendants ();
int rowCntRef = refTableRows.Count;
// check if rowcount is identical
Ranorex.Validate.AreEqual (rowCntAct , rowCntRef , "Comparing number of rows ({0} vs.
{1})");
// run through table -rows
for (int iRow = 0; iRow <= actTableRows.Count - 1; iRow ++)
{
IList cellsInActRow = actTableRows[iRow]. FindChildren <
Ranorex.WebElement >();
IList cellsInRefRow = refTableRows[iRow]. FindChildren <
Ranorex.WebElement >();
// check if number of cells is identical in current row
Ranorex.Validate.AreEqual (cellsInActRow.Count , cellsInRefRow.Count , "
Comparing number of cells in current row ({0} vs. {1})");
// run through cells in current row
for (int iCol = 0; iCol <= cellsInActRow.Count - 1; iCol ++)
{
string aCurText = new WebElement(cellsInActRow[iCol]).InnerText;
string aRefText = new WebElement(cellsInRefRow[iCol]).InnerText;
string validationMessage = string.Empty;
if (string.IsNullOrEmpty(customLogMessageDetail))
{
validationMessage = String.Format ("Comparing content of cell
({2}/{3}) (found:’{0}’, expected: ’{1}’)", aCurText ,
aRefText , iRow ,iCol);
}
else
{
validationMessage = customLogMessageDetail;
}
// validate whether current text and expected text are identical
347
Contents
Ranorex.Validate.AreEqual (aCurText , aRefText , validationMessage);
}
}
// Log overall success
if (string.IsNullOrEmpty(customLogMessageOverall))
customLogMessageOverall = "Successfully completed content -validation of web table with provided snapshot of web -table (reference)";
Ranorex.Report.Log (ReportLevel.Success , customLogMessageOverall);
}
VB.NET
Public Sub Validate_WebTableContentEqual(repoItem As Ranorex.Adapter ,
filename_ReferenceTableSnapshot As String , customLogMessageOverall As String ,
customLogMessageDetail As String)
’ check if snapshot file exists
Ranorex.Validate.IsTrue(System.IO.File.Exists(filename_ReferenceTableSnapshot), String
.Format("Checking existence of snapshot file: {0}",
filename_ReferenceTableSnapshot))
Dim snap As ElementSnapshot
Try
’ ElementSnapshot.CreateFromFile is available starting with Ranorex
5.4.2
snap = Ranorex.Core.ElementSnapshot.CreateFromFile(
filename_ReferenceTableSnapshot)
Catch
Throw New Ranorex.ValidationException("Snapshot could not be loaded from file"
)
End Try
’ restore table from snapshot
Dim refTable As Ranorex.TableTag
Try
refTable = snap.Element
Catch e As Exception
Throw New Ranorex.ValidationException("Table could not be created from
snapshot.", e)
End Try
Dim tableAdapter As Ranorex.TableTag = repoItem .[As](Of Ranorex.TableTag)()
If tableAdapter Is Nothing Then
Throw New Ranorex.ValidationException("Repo -item could not be accessed.")
End If
Dim actTableRows As IList(Of TrTag) = tableAdapter.FindDescendants(Of TrTag)()
Dim rowCntAct As Integer = actTableRows.Count
Dim refTableRows As IList(Of TrTag) = refTable.FindDescendants(Of TrTag)()
Dim rowCntRef As Integer = refTableRows.Count
’ check if rowcount is identical
Ranorex.Validate.AreEqual(rowCntAct , rowCntRef , "Comparing number of rows ({0} vs.
{1})")
’ run through table -rows
For iRow As Integer = 0 To actTableRows.Count - 1
Dim cellsInActRow As IList(Of Ranorex.WebElement) = actTableRows(iRow).
FindChildren(Of Ranorex.WebElement)()
Dim cellsInRefRow As IList(Of Ranorex.WebElement) = refTableRows(iRow).
FindChildren(Of Ranorex.WebElement)()
’ check if number of cells is identical in current row
Ranorex.Validate.AreEqual(cellsInActRow.Count , cellsInRefRow.Count , "Comparing
number of cells in current row ({0} vs. {1})")
’ run through cells in current row
For iCol As Integer = 0 To cellsInActRow.Count - 1
Dim aCurText As String = New WebElement(cellsInActRow(iCol)).InnerText
Dim aRefText As String = New WebElement(cellsInRefRow(iCol)).InnerText
Dim validationMessage As String = String.Empty
If String.IsNullOrEmpty(customLogMessageDetail) Then
validationMessage = [String ]. Format("Comparing content of cell
({2}/{3}) (found:’{0}’, expected: ’{1}’)", aCurText ,
aRefText , iRow , iCol)
Else
validationMessage = customLogMessageDetail
End If
348
Contents
’ validate whether current text and expected text are identical
Ranorex.Validate.AreEqual(aCurText , aRefText , validationMessage)
Next
Next
’ Log overall success
If String.IsNullOrEmpty(customLogMessageOverall) Then
customLogMessageOverall = "Successfully completed content -validation of web table with provided snapshot of web -table (reference)"
End If
Ranorex.Report.Log(ReportLevel.Success , customLogMessageOverall)
End Sub
Advanced Validation - File (text-based)
This sample shows how the content of a text-based file can be validated. The content of the file will be compared
with the content of a reference-file. Therefore the filename of the file to validate needs to be provided as well as the
filename of a reference-file.
C#
public void Validate_FileTextEqual(string filePath_Expected , string filePath_Current , string
customLogMessage)
{
// prepare log messages
const string fileNotFoundMessage = "File not found for comparison in
Validate_FileContentEqual: {0}";
const string logMessage = "Comparing content of files ({0} vs. {1})";
if (string.IsNullOrEmpty(customLogMessage))
{
customLogMessage = string.Format(logMessage , filePath_Expected ,
filePath_Current);
}
// check if file exists
if (! System.IO.File.Exists(filePath_Current))
{
throw new Ranorex.RanorexException(string.Format(fileNotFoundMessage ,
filePath_Current));
}
// check if referencing file exists
if (! System.IO.File.Exists(filePath_Expected))
{
throw new Ranorex.RanorexException(string.Format(fileNotFoundMessage ,
filePath_Expected));
}
// check if filenames are identical
if (filePath_Expected.Equals(filePath_Current))
{
Ranorex.Validate.IsTrue(true , customLogMessage);
}
else
{
string current = System.IO.File.ReadAllText(filePath_Current);
string expected = System.IO.File.ReadAllText(filePath_Expected);
// validate whether expected value equals to current value
Ranorex.Validate.AreEqual(current , expected , customLogMessage);
}
}
VB.NET
Public Sub Validate_FileTextEqual(filePath_Expected As String , filePath_Current As String ,
customLogMessage As String)
349
Contents
’ prepare log messages
Const fileNotFoundMessage As String = "File not found for comparison in
Validate_FileContentEqual: {0}"
Const logMessage As String = "Comparing content of files ({0} vs. {1})"
If String.IsNullOrEmpty(customLogMessage) Then
customLogMessage = String.Format(logMessage , filePath_Expected ,
filePath_Current)
End If
’ check if file exists
If Not System.IO.File.Exists(filePath_Current) Then
Throw New Ranorex.RanorexException(String.Format(fileNotFoundMessage ,
filePath_Current))
End If
’ check if referencing file exists
If Not System.IO.File.Exists(filePath_Expected) Then
Throw New Ranorex.RanorexException(String.Format(fileNotFoundMessage ,
filePath_Expected))
End If
’ check if filenames are identical
If filePath_Expected.Equals(filePath_Current) Then
Ranorex.Validate.IsTrue(True , customLogMessage)
Else
Dim current As String = System.IO.File.ReadAllText(filePath_Current)
Dim expected As String = System.IO.File.ReadAllText(filePath_Expected)
’ validate whether expected value equals to current value
Ranorex.Validate.AreEqual(current , expected , customLogMessage)
End If
End Sub
Advanced Validation - File (non text-based, binary)
This sample shows how a non text-based file (binary file) can be validated. The content of the file will be compared
with the content of a reference-file. Therefore the filename of the file to validate needs to be provided as well as the
filename of a reference-file.
C#
public void Validate_FileBinaryContentEqual(string filePath_Expected , string filePath_Current ,
string customLogMessage)
{
// prepare log messages
const string fileNotFoundMessage = "File not found for comparison in
Validate_FileContentEqual: {0}";
const string logMessage = "Comparing content of files ({0} vs. {1})";
if (string.IsNullOrEmpty(customLogMessage))
{
customLogMessage = string.Format(logMessage , filePath_Expected ,
filePath_Current);
}
// check if file exists
if (! System.IO.File.Exists(filePath_Current))
{
throw new Ranorex.ValidationException (string.Format(fileNotFoundMessage ,
filePath_Current));
}
// check if referencing file exists
if (! System.IO.File.Exists(filePath_Expected))
{
throw new Ranorex.ValidationException(string.Format(fileNotFoundMessage ,
filePath_Expected));
}
// check if filenames are identical
if (filePath_Expected.Equals(filePath_Current))
{
Ranorex.Validate.IsTrue(true , customLogMessage);
350
Contents
}
else
{
using (var file1 = new System.IO.FileStream(filePath_Current , System.IO.
FileMode.Open))
using (var file2 = new System.IO.FileStream(filePath_Expected , System.IO.
FileMode.Open))
// Check whether files are equal
Ranorex.Validate.IsTrue(StreamEquals(file1 , file2), customLogMessage);
}
}
// compare file -streams
private static bool StreamEquals(System.IO.Stream stream1 , System.IO.Stream stream2)
{
const int bufferSize = 2048;
byte[] buffer1 = new byte[bufferSize ];
byte[] buffer2 = new byte[bufferSize ];
while (true)
{
int count1 = stream1.Read(buffer1 , 0, bufferSize);
int count2 = stream2.Read(buffer2 , 0, bufferSize);
if (count1 != count2)
return false;
if (count1 == 0)
return true;
for (int i = 0; i < count1; i++)
{
if (buffer1[i] != buffer2[i])
{
return false;
}
}
}
}
VB.NET
Public Sub Validate_FileBinaryContentEqual(filePath_Expected As String , filePath_Current As
String , customLogMessage As String)
’ prepare log messages
Const fileNotFoundMessage As String = "File not found for comparison in
Validate_FileContentEqual: {0}"
Const logMessage As String = "Comparing content of files ({0} vs. {1})"
If String.IsNullOrEmpty(customLogMessage) Then
customLogMessage = String.Format(logMessage , filePath_Expected ,
filePath_Current)
End If
’ check if file exists
If Not System.IO.File.Exists(filePath_Current) Then
Throw New Ranorex.ValidationException(String.Format(fileNotFoundMessage ,
filePath_Current))
End If
’ check if referencing file exists
If Not System.IO.File.Exists(filePath_Expected) Then
Throw New Ranorex.ValidationException(String.Format(fileNotFoundMessage ,
filePath_Expected))
End If
’ check if filenames are identical
If filePath_Expected.Equals(filePath_Current) Then
Ranorex.Validate.IsTrue(True , customLogMessage)
Else
Using file1 = New System.IO.FileStream(filePath_Current , System.IO.FileMode.
Open)
Using file2 = New System.IO.FileStream(filePath_Expected , System.IO.
FileMode.Open)
’ Check whether files are equal
Ranorex.Validate.IsTrue(StreamEquals(file1 , file2),
customLogMessage)
End Using
351
Contents
End Using
End If
End Sub
’ compare file -streams
Private Shared Function StreamEquals(stream1 As System.IO.Stream , stream2 As System.IO.Stream)
As Boolean
Const bufferSize As Integer = 2048
Dim buffer1 As Byte() = New Byte(bufferSize - 1) {}
Dim buffer2 As Byte() = New Byte(bufferSize - 1) {}
While True
Dim count1 As Integer = stream1.Read(buffer1 , 0, bufferSize)
Dim count2 As Integer = stream2.Read(buffer2 , 0, bufferSize)
If count1 <> count2 Then
Return False
End If
If count1 = 0 Then
Return True
End If
For i As Integer = 0 To count1 - 1
If buffer1(i) <> buffer2(i) Then
Return False
End If
Next
End While
End Function
Advanced Validation - Database (Single Field)
This sample shows how a database-field can be validated against a given text value. To access the database, a valid
connection string needs to be provided as well as a valid SQL Statement. Please see the MSDN for more information
on the OLE database connection.
Note: For performance reasons do not use this method in a series but use the method below to access an entire table
and/or SQL results.
C#
public void Validate_DatabaseFieldWithQuery(string OLEConnectionString , string SQLQuery ,
string expectedValue , string customLogMessage)
{
// check is connection string is empty
if (string.IsNullOrEmpty(OLEConnectionString))
{
throw new Ranorex.RanorexException("ConnectionString is empty");
}
// check if SQL statement is empty
if (SQLQuery.Trim().Equals(string.Empty))
{
throw new Ranorex.RanorexException("SQLQuery is empty");
}
// establish connection to database
using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.
OleDbConnection(@OLEConnectionString))
{
connection.Open();
System.Data.OleDb.OleDbCommand command = null;
System.Data.OleDb.OleDbDataReader SQLReader = null;
try
{
// set SQL statement and execute search
command = new System.Data.OleDb.OleDbCommand(SQLQuery , connection);
SQLReader = command.ExecuteReader ();
SQLReader.Read();
// check if there is a result
if (SQLReader.FieldCount > 0)
352
Contents
{
// retrieve single result from SQL database
var actualValue = SQLReader.GetString (0);
// prepare log message
if (customLogMessage.Trim().Equals(string.Empty))
{
customLogMessage = "Actual value = ’{0}’, expected
value = ’{1}’ (database query = " + SQLQuery + ")"
;
}
// compare retrieved value with expected value
Ranorex.Validate.AreEqual(actualValue , expectedValue ,
customLogMessage);
}
else
{
throw new Ranorex.RanorexException(string.Format("SQL
statement did not return any results: {0}", SQLQuery));
}
}
finally
{
command.Dispose ();
SQLReader.Dispose ();
}
}
}
VB.NET
Public Sub Validate_DatabaseFieldWithQuery(OLEConnectionString As String , SQLQuery As String ,
expectedValue As String , customLogMessage As String)
’ check is connection string is empty
If String.IsNullOrEmpty(OLEConnectionString) Then
Throw New Ranorex.RanorexException("ConnectionString is empty")
End If
’ check if SQL statement is empty
If SQLQuery.Trim().Equals(String.Empty) Then
Throw New Ranorex.RanorexException("SQLQuery is empty")
End If
’ establish connection to database
Using connection As New System.Data.OleDb.OleDbConnection(OLEConnectionString)
connection.Open()
Dim command As System.Data.OleDb.OleDbCommand = Nothing
Dim SQLReader As System.Data.OleDb.OleDbDataReader = Nothing
Try
’ set SQL statement and execute search
command = New System.Data.OleDb.OleDbCommand(SQLQuery , connection)
SQLReader = command.ExecuteReader ()
SQLReader.Read()
’ check if there is a result
If SQLReader.FieldCount > 0 Then
’ retrieve single result from SQL database
Dim actualValue = SQLReader.GetString (0)
’ prepare log message
If customLogMessage.Trim().Equals(String.Empty) Then
customLogMessage = "Actual value = ’{0}’, expected
value = ’{1}’ (database query = " & SQLQuery & ")"
End If
’ compare retrieved value with expected value
Ranorex.Validate.AreEqual(actualValue , expectedValue ,
customLogMessage)
Else
Throw New Ranorex.RanorexException(String.Format("SQL
statement did not return any results: {0}", SQLQuery))
End If
Finally
command.Dispose ()
SQLReader.Dispose ()
353
Contents
End Try
End Using
End Sub
Advanced Validation - Database (Whole Table)
This sample shows how the content of a database can be validated. Using it you can check against an entire table, a
database view or against every result of an SQL statement. Thus a valid SQL statement as well as a valid connection
string has to be provided to allow access to the database. Please see the MSDN for more information on establishing
an OLE database connection.
Additionally, the filename of a csv-file needs to be passed in as a parameter. This file is acts as a reference and should
contain the expected values. If the values in the file are separated differently than using the semicolon (”;”), please
use the parameter ”csvSeparator” to pass it in.
Note: The reference file (csv-file) needs to be created in forefront of calling this method. Every text editor can be
used for creating this reference-file.
C#
public void Validate_DatabaseTableWithQuery(string OLEConnectionString , string SQLQuery ,
string referenceCSVTable , string csvSeparator , string customLogMessageOverall , string
customLogMessageDetail)
{
// check if reference file exists
if (! System.IO.File.Exists(referenceCSVTable))
{
throw new Ranorex.RanorexException(string.Format("File does not exist: {0}",
referenceCSVTable));
}
// check if connection string is empty
if (OLEConnectionString.Trim().Equals(string.Empty))
{
throw new Ranorex.RanorexException("ConnectionString is empty");
}
// check if SQL statement is empty
if (SQLQuery.Trim().Equals(string.Empty))
{
throw new Ranorex.RanorexException("SQLQuery is empty");
}
// prepare separator for csv file (if not passed in)
char separator;
if (string.IsNullOrEmpty(csvSeparator))
{
separator = ’;’;
}
else
{
separator = csvSeparator [0];
}
// establish database connection
using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.
OleDbConnection(@OLEConnectionString))
{
connection.Open();
System.Data.OleDb.OleDbCommand command = null;
System.Data.OleDb.OleDbDataReader SQLReader = null;
System.IO.StreamReader CSVReader = null;
try
{
// set SQL statement and execute search
command = new System.Data.OleDb.OleDbCommand(SQLQuery , connection);
SQLReader = command.ExecuteReader ();
// open csv file (reference file)
354
Contents
CSVReader = new System.IO.StreamReader(System.IO.File.OpenRead(
@referenceCSVTable));
// run through every line in file
int iRow = 0;
while (( SQLReader.Read()) && (! CSVReader.EndOfStream))
{
// read line from csv file
var line = CSVReader.ReadLine ();
// split line into array of values
var values = line.Split(separator);
// check if number of values equals (in current row of csv
file and in SQL result)
if (values.Length != SQLReader.FieldCount)
{
throw new Ranorex.RanorexException(string.Format("
Number of fields in SQL query and reference -file
does not match ({0} vs. {1})", values.Length + 1,
SQLReader.FieldCount));
}
// run through every field in SQL result
for (int iFields = 0; iFields <= SQLReader.FieldCount - 1;
iFields ++)
{
var expectedValue = values[iFields ];
var actualValue = SQLReader[iFields ]. ToString ();
// prepare log message
string validationMessage = string.Empty;
if (string.IsNullOrEmpty(customLogMessageDetail))
{
validationMessage = String.Format("Comparing
content of cell ({2}/{3}) (found:’{0}’,
expected: ’{1}’)", actualValue ,
expectedValue , iRow , iFields);
}
else
{
validationMessage = customLogMessageDetail;
}
// validate if actual value and expected value are
equal
Ranorex.Validate.AreEqual(actualValue , expectedValue ,
customLogMessageDetail);
}
iRow ++;
}
if (string.IsNullOrEmpty(customLogMessageOverall))
{
customLogMessageOverall = "Successfully validated SQL Table
with given SQL -Statement against content of given CSV file
";
}
// Log success
Ranorex.Report.Log(Ranorex.ReportLevel.Success ,
customLogMessageOverall);
}
finally
{
command.Dispose ();
SQLReader.Dispose ();
CSVReader.Dispose ();
}
}
}
VB.NET
Public Sub Validate_DatabaseTableWithQuery(OLEConnectionString As String , SQLQuery As String ,
referenceCSVTable As String , csvSeparator As String , customLogMessageOverall As String ,
customLogMessageDetail As String)
355
Contents
’ check if reference file exists
If Not System.IO.File.Exists(referenceCSVTable) Then
Throw New Ranorex.RanorexException(String.Format("File does not exist: {0}",
referenceCSVTable))
End If
’ check if connection string is empty
If OLEConnectionString.Trim().Equals(String.Empty) Then
Throw New Ranorex.RanorexException("ConnectionString is empty")
End If
’ check if SQL statement is empty
If SQLQuery.Trim().Equals(String.Empty) Then
Throw New Ranorex.RanorexException("SQLQuery is empty")
End If
’ prepare separator for csv file (if not passed in)
Dim separator As Char
If String.IsNullOrEmpty(csvSeparator) Then
separator = ";"C
Else
separator = csvSeparator (0)
End If
’ establish database connection
Using connection As New System.Data.OleDb.OleDbConnection(OLEConnectionString)
connection.Open()
Dim command As System.Data.OleDb.OleDbCommand = Nothing
Dim SQLReader As System.Data.OleDb.OleDbDataReader = Nothing
Dim CSVReader As System.IO.StreamReader = Nothing
Try
’ set SQL statement and execute search
command = New System.Data.OleDb.OleDbCommand(SQLQuery , connection)
SQLReader = command.ExecuteReader ()
’ open csv file (reference file)
CSVReader = New System.IO.StreamReader(System.IO.File.OpenRead(
referenceCSVTable))
’ run through every line in file
Dim iRow As Integer = 0
While (SQLReader.Read()) AndAlso (Not CSVReader.EndOfStream)
’ read line from csv file
Dim line = CSVReader.ReadLine ()
’ split line into array of values
Dim values = line.Split(separator)
’ check if number of values equals (in current row of csv file
and in SQL result)
If values.Length <> SQLReader.FieldCount Then
Throw New Ranorex.RanorexException(String.Format("
Number of fields in SQL query and reference -file
does not match ({0} vs. {1})", values.Length + 1,
SQLReader.FieldCount))
End If
’ run through every field in SQL result
For iFields As Integer = 0 To SQLReader.FieldCount - 1
Dim expectedValue = values(iFields)
Dim actualValue = SQLReader(iFields).ToString ()
’ prepare log message
Dim validationMessage As String = String.Empty
If String.IsNullOrEmpty(customLogMessageDetail) Then
validationMessage = [String ]. Format("Comparing
content of cell ({2}/{3}) (found:’{0}’,
expected: ’{1}’)", actualValue ,
expectedValue , iRow , iFields)
Else
validationMessage = customLogMessageDetail
End If
’ validate if actual value and expected value are
equal
Ranorex.Validate.AreEqual(actualValue , expectedValue ,
customLogMessageDetail)
Next
iRow += 1
End While
If String.IsNullOrEmpty(customLogMessageOverall) Then
customLogMessageOverall = "Successfully validated SQL Table
with given SQL -Statement against content of given CSV file
356
Contents
"
End If
’ Log success
Ranorex.Report.Log(Ranorex.ReportLevel.Success ,
customLogMessageOverall)
Finally
command.Dispose ()
SQLReader.Dispose ()
CSVReader.Dispose ()
End Try
End Using
End Sub
Advanced Validation - XML code
This sample shows how XML code can be validated with Ranorex. The method below awaits the XML code snippet
as a parameter and an XPath expression in the parameter ’node’. This XPath expression selects the node to validate.
Please provide the expected value as well in the parameter ’expectedValue’.
Use case and example: This method might be useful to validate the result of a web service in XML format. Assuming
an online library provides a web service allowing to gather detailed information of books when submitting a unique
ISBN. The result from the web service is in XML format and contains information like author, title, year of publication
and more of the found book. The XML result (see sample XML code below) can now be validated using the code
method with the following call:
C#
// call method to validate xml code
Validate_XMLResponse(xml , "
VB.NET
’ call method to validate xml code
Validate_XMLResponse(xml , "
Note: This method can also be called from the recorder’s action table. Therefore the usercode file needs to provide
this method (directly or derived from a base class).
C#
public void Validate_XMLResponse(string xmlContent , string node , string expectedValue , string
customLogMessage)
{
string actualValue = string.Empty;
// check if xml content is empty
if (string.IsNullOrEmpty(xmlContent))
{
throw new Ranorex.ValidationException ("Parameter ’xmlContent ’ is empty");
}
// check if node (XPath) is empty
if (string.IsNullOrEmpty(node))
{
throw new Ranorex.ValidationException("Parameter ’node ’ is empty");
}
// check if expected value is empty
if (string.IsNullOrEmpty(expectedValue))
{
throw new Ranorex.ValidationException("Parameter ’expectedValue ’ is empty");
357
Contents
}
System.Xml.XmlDocument document = new System.Xml.XmlDocument ();
try
{
// load XML from text in xml file
document.LoadXml(xmlContent);
// select the node with given argument (XPath)
System.Xml.XmlNode desiredNode = document.SelectSingleNode(node);
if (desiredNode != null)
{
actualValue = desiredNode.InnerText;
}
else
{
throw new Ranorex.ValidationException(string.Format("No node found
with XPath ’{0}’!", node));
}
}
catch (System.Xml.XmlException)
{
throw new Ranorex.ValidationException("Unable to load valid XML string!");
}
// prepare log file
if (string.IsNullOrEmpty(customLogMessage))
{
customLogMessage = "Comparing XML response ({0} vs. {1})";
}
// validate if expected value and actual value are equal
Ranorex.Validate.AreEqual(expectedValue , actualValue , customLogMessage);
}
VB.NET
Public Sub Validate_XMLResponse(xmlContent As String , node As String , expectedValue As String ,
customLogMessage As String)
Dim actualValue As String = String.Empty
’ check if xml content is empty
If String.IsNullOrEmpty(xmlContent) Then
Throw New Ranorex.ValidationException("Parameter ’xmlContent ’ is empty")
End If
’ check if node (XPath) is empty
If String.IsNullOrEmpty(node) Then
Throw New Ranorex.ValidationException("Parameter ’node ’ is empty")
End If
’ check if expected value is empty
If String.IsNullOrEmpty(expectedValue) Then
Throw New Ranorex.ValidationException("Parameter ’expectedValue ’ is empty")
End If
Dim document As New System.Xml.XmlDocument ()
Try
’ load XML from text in xml file
document.LoadXml(xmlContent)
’select the node with given argument (XPath)
Dim desiredNode As System.Xml.XmlNode = document.SelectSingleNode(node)
If desiredNode IsNot Nothing Then
actualValue = desiredNode.InnerText
Else
Throw New Ranorex.ValidationException(String.Format("No node found
with XPath ’{0}’!", node))
End If
Catch generatedExceptionName As System.Xml.XmlException
Throw New Ranorex.ValidationException("Unable to load valid XML string!")
End Try
’ prepare log file
If String.IsNullOrEmpty(customLogMessage) Then
customLogMessage = "Comparing XML response ({0} vs. {1})"
End If
’ validate if expected value and actual value are equal
Ranorex.Validate.AreEqual(expectedValue , actualValue , customLogMessage)
358
Contents
End Sub
Below there is the a sample XML code allowing you to implement the sample from above.
XML




359
Contents
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
ˆ CSV File
ˆ SQL Connector
ˆ 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.
Figure 388: Open ’Manage Data Sources’ dialog from test suite view
360
Contents
Figure 389: ’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.
361
Contents
Figure 390: Set up data sources for a test case
Figure 391: 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, e.g. ’1-5, 8, 11-13’), press the purple
marked button, labeled ’Preview effective data set. . . ’.
362
Contents
Figure 392: 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 CSV file by pressing the red marked button,
labeled ’Export CSV’.
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 Creating
Test Data. In this dialog choose one of the following data connector types from the combo box labeled ’New’.
ˆ Simple Data Table
ˆ CSV File
ˆ SQL Connector
ˆ Excel File
363
Contents
Simple Data Table
This Data Connector 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.
Figure 393: New created simple data table
364
Contents
Figure 394: Add new test data directly to a table of type ’Simple Data Connector’
To protect proprietary data like passwords you can mask specific columns of your data source. To do so, open the
Manage Data Sources dialog, choose the connector and select the column you want to mask.
365
Contents
Figure 395: Choose the column you want to mask
366
Contents
CSV File
You can also use a CSV file to provide data for your test suite by choosing this type of data connector. After adding
a CSV 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 CSV 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 CSV 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 CSV file will be added as the
header of all rows.
Figure 396: Set up CSV file as external data source
To protect proprietary data like passwords you can mask specific columns of your data source.
CSV 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 CSV 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 CSV file.
367
Contents
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 ’Create’ button. After establishing a connection to the database by
generating a connection string, you can add an SQL query by pressing the green marked ’Create’ button.
Figure 397: Set up SQL connector - main dialog
After setting up the connector you can mask specific columns of your data source to protect proprietary data like
passwords.
Create Connection String
By pressing the red marked ’Create’ button in the data source management dialog the connection properties dialog
will be opened.
368
Contents
Figure 398: SQL connector - Connection Properties dialog
The appearance of this dialog depends on the data source which can be chosen by pressing the ’Change’ 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 Connection’.
Create Query
By pressing the green marked ’Create’ button in the data source management dialog the query design dialog will be
opened.
369
Contents
Figure 399: 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.
370
Contents
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.
Figure 400: Create new Excel file connector
To protect proprietary data like passwords you can mask specific columns of your data source.
Note: Instead of using the default Excel file format xlsx for your test data you can also use the native
binary file format xlsb. This file format is supported since Microsoft Office 2007 and is much faster than the
non-binary version.
371
Contents
Instrumentation Wizard
Note: 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 (\bin\Ranorex.InstrumentationWizard.exe). The last method is useful if
you are going to automatically instrument a technology. Have a look at the section ’Running Instrumentation Wizard
from the Command Line’ for further details.
The wizard is used to instrument the following technologies:
ˆ Java AWT/Swing
ˆ Adobe Flash/Flex
ˆ Mozilla Firefox
ˆ Google Chrome
ˆ Apple Safari
ˆ Android
ˆ iOS
Figure 401: Start Instrumentation Wizard from Ranorex Tools Menu
Figure 402: Start Instrumentation Wizard from Technology Limitation
372
Contents
Figure 403: Start Instrumentation Wizard from installation folder
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.
373
Contents
Figure 404: Instrumentation Wizard
Running Instrumentation Wizard from the Command Line
Using the following arguments, you can execute the ’Instrumentation Wizard’ from the command line. This is required
for automated command line based instrumentation.
Ranorex.Instrumentation.exe /
p|pagename:
Default is ’Select’. Set this option to directly navigate to a specific page. Is also required for automated command
line based instrumentation.
Pages are: android, chrome, firefox, flex, ios, java and safari.
Note: The default ’Select’ is not supported in the command line.
?|help:
Default is False. Displays command line arguments help.
Pagename specific arguments:
android
d|device: The name of the device to that the APK file shall be deployed. This parameter is not required if deploymode
is set to ’NoDeploy’.
a|apkfile: Required. The path where the APK file resides.
s|skip: Default is False. Set this switch to skip APK file instrumentation prior to deploying.
374
Contents
dm|deploymode: Possible Values: WiFi, Usb, NoDeploy, Auto. Default is Auto. Specifies how the apk file shall be
deployed. Set to nodeploy if the file shall not be deployed to the device. Auto means the connection mechanism used
to configure the device will be used.
o|outfile: Sets a custom output location for the instrumented file. This can be a directory or a file path. Read/Write
permission is required for this path. If a directory was specified, (to specify a directory add a trailing ’\’) the process
will place the APP file in it with the -instrumented suffix added to the source file name. If the file already exists it will
be overwritten. This option only has an effect if an APP is instrumented (no skip).
android Advanced options: APK Signing
JdkBinPath: Full Path to your JDK installation bin folder.
KeyAlias: Alias of the keystore entity used for jarsigner.
KeyPass: Password of the key used for jarsigner. Warning: Please note that password is stored in plain text. Do
not use production certificates.
KeyStore: Location (full path) of the keystore used for jarsigner.
KeyStorePass: Password of the keystore used for jarsigner. Warning: Please note that password is stored in plain
text. Do not use production certificates.
Note: For custom signing, Keystore, Keystore alias, Keystore password, Key password and JDK bin path
have to be set.
android Advanced Options: Instrumentation Options
RIdClass: Provide a custom class name for locating resource ids (e.g. com.ranorex.demo.R). By default Ranorex will
search id in .R.
EnableWebTesting: When set to true Ranorex shows DOM content of Web Views in UI-Hierarchy. Note that this
feature has a huge performance impact on your app. Default is true.
FullImageComparison: When enabled, more robust image comparison is used to determine resource id’s for images.
This option decreases startup performance.
TreeSimplification: When set to false, no post processing of the UI-Tree takes place. This results in a larger UI-Tree
which could be useful for automating 3rd party Android controls.
android
d|device: The name of the device to that the APK file shall be deployed. This parameter is not required if deploymode
is set to ’NoDeploy’.
a|apkfile: Required. The path where the APK file resides.
s|skip: Default is False. Set this switch to skip APK file instrumentation prior to deploying.
dm|deploymode: Possible Values: WiFi, Usb, NoDeploy, Auto. Default is Auto. Specifies how the apk file shall be
deployed. Set to nodeploy if the file shall not be deployed to the device. Auto means the connection mechanism used
to configure the device will be used.
o|outfile: Sets a custom output location for the instrumented file. This can be a directory or a file path. Read/Write
permission is required for this path. If a directory was specified, (to specify a directory add a trailing ’\’) the process
will place the APP file in it with the -instrumented suffix added to the source file name. If the file already exists it will
be overwritten. This option only has an effect if an APP is instrumented (no skip).
375
Contents
chrome
e|enable: Required. Enable this switch to activate Chrome browser addon. If the switch is disabled the addon will be
deactivated.
firefox
e|enable: Required. Enable this switch to activate FireFox browser addon. If the switch is disabled the addon will be
deactivated.
flex
pl|preloader: Required. Enable this switch to enable the Ranorex preloader. If the switch is disabled the preloader
will get deactivated.
ie: Enable this switch to enable Internet Explorer Flex debug player. If the switch is disabled Internet Explorer Flex
debug player will get deactivated.
ff|firefox: Enable this switch to enable the Firefox/Safari NPAPI Flex debug player. If the switch is disabled
Firefox/Safari Flex debug player will get deactivated.
cr|chrome: Enable this switch to enable the Chrome PPAPI Flex debug player. If the switch is disabled the Chrome
PPAPI Flex debug player will get deactivated.
o|other: Enable this switch to enable the Chrome *and* Firefox Flex debug player. If the switch is disabled the
Chrome and Firefox Flex debug player will get deactivated. [Obsolete option use /cr and/or /ff instead.]
ft|flextrace: Default is False. Enable this switch to enable Flash tracelog. If the switch is disabled flash trace log will
get deactivated.
java
jp|javapath: Required. System path to the JRE.
d|disable: Default is True. Tells Ranorex that the instrumentation should be removed.
safari
e|enable: Required. Enable this switch to activate Safari browser addon. If the switch is disabled the addon will be
deactivated.
ios
u|udid: The unique device identifier for the device on that the application shall be installed (Note: instead of UDID
the new option ’devicename’ can be used). To get the UDID start Ranorex Studio open the manage devices dialog
and select your device (that was added as a USB device) and click edit. In the meta data field you will find the UDID
of the device.
dn|devicename: The name of the device. You can specify the name instead of the UDID. The name needs to exactly
match the name, you set for your device in the settings app of that device.
ip|inputpath: The path to the application archive (*.ipa).
o|outfile: Sets a custom output location for the instrumented file. This can be a directory or a file path. Read/Write
permission is required for this path. If a directory was specified, (to specify a directory add a trailing ’\’) the process
will place the APP file in it with the -instrumented suffix added to the source file name. If the file already exists it will
be overwritten. This option only has an effect if an APP is instrumented (no skip).
si|skipinstrumentation: Default is False. Set this switch to skip IPA file instrumentation.
376
Contents
sd|skipdeployment: Default is False. Set this switch to skip IPA file deployment.
k|keypath: The path to the p12 key file (*.p12).
pw|password: The password for the p12 key file.
pp|provisionpath: The path to the embedded mobile provision file (*.mobileprovision).
ai|appid: Default is . The application Id (bundle identifier of the app). This is required so that an application can be
uninstalled prior to installing the new archive. Can be set to ’[auto]’ to resolve it automatically during instrumentation.
db|deploybrowser: Default is False. Set this switch to deploy Ranorex browser app.
ds|deployservice: Default is False. Set this switch to deploy Ranorex service app.
ub|uninstallbrowser: Default is False. Set this switch to uninstall Ranorex browser before deploy
us|uninstallservice: Default is False. Set this switch to uninstall Ranorex service before deploy
uf|uninstallfail: Default is False. Set this switch to throw exception when uninstalling an app fails.
377
Contents
Java AWT/Swing
The Ranorex Java Plug-In allows testing of Java Swing and Java AWT applications. With Ranorex 5.0.0 and higher,
the instrumentation will be enabled automatically. If you have instrumented your Java Runtime Environment using
the Ranorex Instrumentation Wizard of a previous Ranorex version, it’s recommended to deactivate the obsolete
instrumentation. To do so, start the Ranorex Instrumentation Wizard from command line with argument ’/p:java’:
\Bin>Ranorex.InstrumentationWizard.exe /p:java
The Instrumentation Wizard tries to remove the obsolete Plug-In specific files from the Java Runtime Environment
(JRE) of your choice.
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 under test. 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
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.
Figure 405: Java Instrumentation Wizard
After deactivating the obsolete Java AWT/Swing instrumentation, restart your application under test and your
Ranorex tools to ensure that the automatically added instrumentation works correctly.
378
Contents
Figure 406: Finished Java Instrumentation
379
Contents
Adobe Flash/Flex
The Flash/Flex technology limitation will pop up if your Flash/Flex application is not instrumented correctly.
Figure 407: Flash/Flex Technology Limitation
Note: If you need to automate an Adobe AIR application, please read Methods for loading the Automation
Lib chapter.
The instrumentation Wizard tries to install the Flash Debug Player for Internet Explorer and the Flash
Debug Player for Mozilla Firefox and Safari and the Flash Debug Player for Google Chrome 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.
380
Contents
Figure 408: Flash/Flex Instrumentation Wizard
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.
Figure 409: 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.
381
Contents
Google Chrome
To use the preloader method with Google Chrome, you have to disable the internal Flash Player. This can be done by
performing following steps:
ˆ Open Chrome’s plugins overview (chrome://plugins/):
Figure 410: Open plug-ins overview
ˆ Display the Plug-Ins details:
Figure 411: Plug-In in detail
ˆ Disable the internal Flash Player (framed red) and keep the Flash Debug Player (framed green) enabled:
382
Contents
Figure 412: Disable the internal Flash Player
383
Contents
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.
Figure 413: 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.
Figure 414: 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.
384
Contents
Figure 415: 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.
Figure 416: 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.
385
Contents
Figure 417: Confirm Ranorex Automation Add-On installation
386
Contents
Google Chrome
The Chrome technology limitation will pop up if the Ranorex Extension for the Chrome Browser is not installed or
enabled.
Figure 418: Google Chrome Technology Limitation
The Instrumentation Wizard opens the Chrome web store page when pressing the ’Next’ button. You can install the
Extension by clicking the + sign in the store page.
Figure 419: 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.
387
Contents
Figure 420: Finished Google Chrome Instrumentation
When not using the default Chrome user profile, you have to add the Ranorex Chrome Add-On manually. To do so,
open the Chrome Extensions settings (chrome://extensions), enable ’Developer mode’ and press the ’Load unpacked
extension’ button. After choosing the ’Ranorex Chrome Extension’ folder (\Ranorex
Chrome Extension) and confirming the new Extension, the Ranorex Add-On will be listed on the Extensions page.
388
Contents
Figure 421: Load Ranorex Chrome Extension
Figure 422: Confirm Extension
389
Contents
Figure 423: Installed Ranorex Automation Extension
Note: If you want to test cross domain iframe scripting with Google Chrome, you have to start Chrome with
the command line argument ’--disable-web-security --user-data-dir=”” ’.
Note: Verify that the extension ID (see screenshot above) is listed in the ”allowed origins” section of
\bin\Ranorex.Plugin.ChromeMsgHost.manifest file.
Note: If you want to test file URLs, you have to enable ’Allow access to file URLs’ for the Ranorex Automation
Extension.
Figure 424: Allow access to file URLs
390
Contents
Note: If the NotScript Chrome Extension is installed, it has to be disabled to allow from point tracking with
Ranorex.
391
Contents
Apple Safari
The Safari technology limitation will pop up if the Ranorex Extension for the Safari Browser is not installed or enabled.
Figure 425: 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.
Figure 426: Apple Safari Instrumentation Wizard
After activating the Extension, you have to confirm the installation in Safari.
392
Contents
Figure 427: 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.
Figure 428: 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.
393
Contents
Figure 429: 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).
Figure 430: 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.
394
Contents
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 Getting Started to learn how to automate Android applications.
Note: Note: It’s recommended to fresh instrument your app for every new Ranorex release. For further
information have a look at the section ’Versioning’.
Figure 431: Android instrumentation wizard
Next to instrumenting and deploying your Android app, the Instrumentation Wizard allows you to update the Ranorex
Service on your device as well as deploy the RXBrowser app, which enables Testing of Mobile Websites on Android.
Choose 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
App under test’ 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.
395
Contents
Figure 432: Finished Android instrumentation
The instrumented APK file can be found at location referenced by the link ’Open instrumentation File location’.
After instrumenting and deploying the APK file, the app is available in the ’Record a Mobile Test’ section of Record
Setting dialog.
Figure 433: Choose mobile as technology
396
Contents
Figure 434: Instrumented APK in Record Settings
The Ranorex Service App installed on the mobile device shows an overview of instrumented apps installed on the
device.
Figure 435: Overview of instrumented APKs
Note: If you have problems with instrumenting your APK using the instrumentation wizard or if you want to
integrate the instrumentation into your build process, please have a look at the ”Instrumentation with Source
Code” section.
397
Contents
iOS
To make an iOS app automatable by Ranorex, it is necessary to instrument this application and deploy it to a device.
The Instrumentation wizard can be used to deploy the instrumented app to the device.
Note: Deployment only works for USB connected iOS devices.Have a look at Instrumentation and Preparation
to learn how to instrument iOS applications.
Note: Note: It’s recommended to fresh instrument your app for every new Ranorex release. For further
information have a look at the section ’Versioning’.
Figure 436
398
Contents
Figure 437
Next to instrumenting and deploying your iOS app, the Instrumentation Wizard allows you to update the Ranorex
Service on your device as well as deploy the RXBrowser app, which enables web testing for iOS.
Choose the IPA file of the app and the device, the app will be deployed to.
To instrument the IPA file of the app, a p12 key file, the corresponding password and the mobileprovision file are
necessary.
Note: The iOS signing needs to be configured only once. The settings will be saved for future IPA files
instrumentation.
More information about setting up a mobile device and deploying from windows machines can be found in the section
iOS Testing.
To delete the existing version of the app on your device before deploying a new one, check the corresponding check
box.
399
Contents
Figure 438: Finished iOS instrumentation
The instrumented IPA file can be found at location referenced by the link ’Open Instrumentation File location’.
After instrumenting and deploying the IPA file, the app is available in the ’Record a Mobile Test’ section of Record
Setting dialog.
Figure 439: Instrumented APK in Record Settings
Note: iOS application packages (IPA files) that have been downloaded from the App Store will not be
instrumented correctly, because they have the DRM (Digital Rights Management) restriction.
400
Contents
Note: Because the Ranorex automation lib uses non-public APIs, make sure that you do not submit a
Ranorex instrumented app to the app store as your app might be rejected and you might be banned from
submitting apps to the app store for a period of time.
401
Contents
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.
Figure 440: 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
ˆ Testing of SAP Applications
ˆ Testing of CEF applications
ˆ General Troubleshooting
402
Contents
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
The automation of Flash/Flex applications requires inclusion of the Ranorex Flex Automation Lib.
ˆ Using the Ranorex PreLoader
ˆ OR including the Ranorex Lib into Adobe Flex: Adobe Flex: Load the Ranorex Lib into your Flex applicationinto Adobe Flash: Adobe Flash: Load the Ranorex Lib into your Flash application
Samples
A flash/flex test sample project is included with the Ranorex installation package (shown on the startpage of Ranorex
Studio).
ˆ How to read/set attributes and styles
Methods for loading the Automation Lib
Depending on your flash/flex application, you can choose to use one of the following flexible instrumentation methods:
Using the Ranorex PreLoader
The Ranorex PreLoader enables automation of your flash/flex application without modifying the application itself.
ˆ Adobe Flash/Flex
ˆ No modifications to your application needed
ˆ Adobe Flash Debug Player has to be installed on the runtime machine
Adobe Flex: Load the Ranorex Lib into your Flex application
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
How to load the Ranorex Module into your Flash application
The Module swf file has to be loaded by adding a code snippet to your How to load the Ranorex Module into your
Flash application or to your How to load the Ranorex Module into your Flex/AIR application.
ˆ Module will be loaded in background (will not affect the functionality of your flash/flex application)
ˆ No modifications to your website needed
403
Contents
ˆ 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:
Flash Flex AIR*
CS3 CS4 CS5 3.X 4.X 2.X 3.X 4.X
PreLoader
Automation Lib
Module
* Support for Adobe AIR 2 Release in combination with Flex 3.5 and Flex 4 Release
Figure 441
= supported
Figure 442
= recommended
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,
Chrome and Safari). You can add user code actions to your recordings to access custom Flex properties.
404
Contents
Figure 443: Test Automation of Flash/Flex Applications
How to read/set attributes and styles
You can read/set common attributes (e.g. the checkstate of a checkbox) directly by using the adapter as follows:
// 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:
// 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 ’]");
containerFlex.SetStyle("borderColor","#ee0000");

Using the Ranorex PreLoader
The Adobe Flash/Flexautomatically activates Flash/Flex automation for your machine as Adobe Flash/Flex.
If the automatic instrumentation did not work, you can follow these steps to achieve what the Instrumentation Wizard
would have done:
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 (Windows 8: x86 / x64 and Windows 8.1: x86 / x64)
ˆ Firefox / Safari
ˆ Chrome
2. Open your user profile directory %UserProfile%, e.g. by opening Windows Explorer and copying the string
%UserProfile% into the address bar.
405
Contents
3. Create a new file called ’mm.cfg’ in your user profile directory and insert the following line of code:
PreloadSwf= C:Program Files\Ranorex X.X\Bin\RanorexAutomation.swf
where ’C:\Program Files\Ranorex X.X\Bin\RanorexAutomation.swf’ needs to be replaced by the preloader
location of your Ranorex installation. If the ’mm.cfg’ file already exists, check if the location is correctly set to
your current preloader location (Ranorex X.X might change after upgrading to a new version!). In addition
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 the logging information to our support team. To enable logging you have to add (or modify) 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\AppData\Roaming\Macromedia\Flash Player\Logs
where needs to be replaced by the username that is logged on.
4. If you run your application from the local drive, add your output directory to the trusted locations of Flash
Player as follows:
(a) Open following link http://www.macromedia.com/support/documentation/en/flashplayer/help/settings
manager04.html#119065
(b) Add your project output directory
Adobe Flex: Load the Ranorex Lib into your Flex application
1. Start Adobe Flash Builder and open your workspace
2. Right-click on your project and choose Properties
3. Under Flex Compiler add the RanorexAutomation.swc file (located in the Bin directory of your Ranorex
installation) to the the compiler argument as follows:
-include -libraries "C:/ Program Files/Ranorex X.X/Bin/RanorexAutomation.swc"
4. Append following code to your ’applicationCompleteHandler’ function:
import Ranorex.RxAutomation;
RxAutomation.Init();
5. Save and compile your application
6. Run your application in a supported browser (Internet Explorer, Firefox, Chrome, 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:
(a) Open following link http://www.macromedia.com/support/documentation/en/flashplayer/help/settings
manager04.html
(b) Add your project output directory
406
Contents
Adobe Flash: Load the Ranorex Lib into your Flash application
1. Start Adobe Flash CS4/CS5 and open your application
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 ACTIONS (by pressing F9):
import Ranorex.RxAutomation;
RxAutomation.InitFromApp(stage);
OR add the code to your ActionScript source file as follows:
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, Chrome, 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:
(a) Open following link http://www.macromedia.com/support/documentation/en/flashplayer/help/settings
manager04.html
(b) Add your project output directory
How to load the Ranorex Module into your Flash application
1. Start Adobe Flash CS3/CS4/CS5 and open your application
2. Insert following code to your ACTIONS (by pressing F9):
3. Copy 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, Chrome, 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:
(a) Open following link http://www.macromedia.com/support/documentation/en/flashplayer/help/settings
manager04a.html#119065
(b) Add your project output directory
407
Contents
How to load the Ranorex Module into your Flex/AIR application
1. Start Adobe Flash Builder and open your workspace
2. Append following code to your ’applicationCompleteHandler’ function or initialization code: For Flex 3:
3. Copy 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, Chrome, 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:
(a) Open following link http://www.macromedia.com/support/documentation/en/flashplayer/help/settings
manager04.html
(b) Add your project output directory
408
Contents
Testing of Java Applications
The Ranorex Java Plug-In allows testing of Java Swing and Java AWT applications. With Ranorex 5.0.0 and
higher, the instrumentation will be enabled automatically. If you have instrumented your Java Runtime Environment
using the Ranorex Instrumentation Wizard of a previous Ranorex version, it’s recommended to deactivate the obsolete
instrumentation. To do so, either use the Java AWT/Swing or manually delete the Plug-In specific files as shown
below.
Figure 444: Java Instrumentation Wizard
Manual Disable obsolete Ranorex Java Plug-In
1. First of all close all Ranorex Tools.
2. Now you have todetermine 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 Control 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.
3. After identifying the path, you have to delete each of the following files from its corresponding directory based
on the root folder of your java runtime installation (e.g. ’C:\Program Files (x86)\Java\jre6\’).
ˆ ’accessibility.properties’ from \lib
ˆ ’RanorexAutomation.jar’ from \lib\ext
ˆ ’JavaHelper32/64.dll’ from \bin
409
Contents
Qt Testing
The Ranorex Automation Framework fully supports out-of-the-box test automation of Qt based applications.
Qt versions:
ˆ Qt Widgets: Qt version 4.5.3 or higher
ˆ Qt Quick: Qt version 5.0.2 or higher
ˆ Qt WebKit: Qt version 4.6.4 or higher
There is no need for a manual instrumentation, it will be done automatically.
Only dynamically linked Qt applications are supported.
To go back to MSAA (Microsoft Active Accessibility) and Qt Accessibility recognition, the ’Qt legacy automation
mode’ can be enabled in the ’Plugin Specific Settings’.
When ’Qt legacy automation mode’ has been enabled, MSAA support for your Qt application must be enabled to
ensure that Ranorex can access UI elements and properties in the Qt application. 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. Copy 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. Create 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
410
Contents
Figure 445: Without Accessible Plug-in
Figure 446: With Accessible Plug-in
411
Contents
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.
Figure 447: 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.
412
Contents
Figure 448: Before . . .
Figure 449: . . . 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 Capture Settings’ button to edit the list of
captured class names and processes.
413
Contents
Figure 450: 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.
414
Contents
Testing of SAP Applications
To provide access to SAP GUI windows and elements, SAP Scripting support needs to be enabled in SAP GUI.
Enable SAP Scripting Support
To do so, open the SAP GUI options dialog and enable scripting in the ’Accessibility and Scripting’ section. Additionally
deactivate the notification options as shown in the following figure.
Figure 451: SAP GUI options dialog
Note: The administrator has to enable the support by setting the profile parameter sapgui/user scripting to
”TRUE” on the application server.
415
Contents
Testing of CEF applications
Starting with Ranorex 6.2, you can test web content in desktop applications that are based on these chromium-based
frameworks:
ˆ Chromium Embedded Framework (CEF)
ˆ CefSharp
ˆ Electron
ˆ NW.Js
ˆ Qt WebEngine
Preparing the application under test
To start testing CEF applications with Ranorex, you have to enable the remote debugging port in the application
under test (AUT).
You can do so by using the command line argument ’remote-debugging-port’ when starting the AUT. For example:
MyApplicationUnderTest.exe --remote-debugging-port=8081
The port number you are using in this command must not be used by another application or service on the windows
machine you are testing the AUT.
In a Ranorex recording you can add this command line argument to the ’Run Application’ action.
CefSharp applications
If your AUT is based on CefSharp, the command line argument does not work. Please enable the remote debugging
port in the source code of the AUT.
To set the remote debugging port in CefSharp, you have to specify it with help of the CefSettings class before initializing
the control like this: var settings = new CefSettings(); settings.RemoteDebuggingPort = 8081; Cef.Initialize(settings);
Technology Limitations
When testing CEF applications, you may come across a technology warning. Here are potential causes for these
technology warnings:
Another application is already listening on the remote debugging port
If another application on the machine is already listening on the remote debugging port of the application under test,
Ranorex cannot connect to the AUT.
By Default, Ranorex tries to close these applications. In some cases, like the Chrome Developer Tools, this is not
successful. That is why a manual action from the user is needed.
Please try to:
ˆ Close all other applications, like the Chrome Development Tools, that may have a connection to the application
under test at the remote debugging port.
ˆ Choose a different port number as remote debugging port for the application under test.
416
Contents
CEF UI element invisible
The UI element containing the CEF control is not visible. In order to test the web content inside the CEF control, the
containing UI element has to be visible.
Please try to:
ˆ Include an action in your recording to make sure the UI element is visible.
Remote debugging not available
The remote debugging interface of the application under test is not available. However, this is a prerequisite for
testing CEF applications with Ranorex.
Please try to:
ˆ Make sure the application under test is correctly Preparing the application under test.
ˆ The port number used as remote debugging port must not be used by any other application on the machine.
ˆ Make sure no other application on the machine listens to the remote debugging port the application under test
provides.
417
Contents
General Troubleshooting
This section provides an overview of possible reasons for a limited object recognition with Ranorex tools and
recommends ways to correct a malfunction.
ˆ .NET WinForms
ˆ .NET WPF
ˆ .NET Silverlight
ˆ Flash/Flex Applications
ˆ Win32 Based Applications
ˆ Browser (Mozilla Firefox, Google Chrome, Apple Safari, Microsoft Internet Explorer)
ˆ Image Related Automation or Validation
ˆ Geometry Related Issues
ˆ Windows Apps (aka Windows 8 UI Apps)
ˆ Other Software
ˆ Different Display DPI Scaling Values
.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 .NET Framework 4 (or higher) got installed after Ranorex was already installed and the AUT uses .NET 4.0.
Consequently, as the .NET Framework 4 was not present when Ranorex was installed, the Ranorex setup could not
install the DLLs required to recognize and automate .NET 4.0 applications.
Solution:
Uninstall Ranorex completely and then re-install Ranorex.
418
Contents
Reason #4:
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 #5:
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 CPU’ (Ranorex Studio) or ’Platform Target’ (Visual Studio) option in the automation
project settings to match the target of the automated application as described in 64-bit Platforms. If you don’t know
the target CPU/platform of the automated application, first try to change the option to ’Any processor’ or ’Any
CPU’, respectively, then try the remaining options.
Reason #6:
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
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 #7:
If the application under test is built with the .NET Framework 4.0, a .exe.config file (where
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:
Create 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 .exe.config file in the same folder as the Ranorex executable
with following content:





.NET WPF
For compatibility with existing tests, Ranorex 5.3+ shows WPF windows twice in its tree; once using the WPF-specific
plug-in, another time using UIAutomation. When selecting a specific element, the UIAutomation tree was chosen,
although the native WPF plug-in is available and active.
419
Contents
Reason #1:
While selecting an element of a WPF application in the element-tree of Spy, you selected the UIAutomation tree of
that application.
Solution:
The preceding sibling of the selected window will identify the same window, but provide the ”WpfElement” capability
instead of ”UiAutomation”. When browsing elements in Spy, select elements below the ”WpfElement” window.
Reason #2:
Instrumentation of the WPF application has failed, because the application runs on a .NET 3.0 runtime, and .NET
3.5 is not installed.
Solution:
Upgrade the .NET installation to version 3.5. No changes are required for the application under test.
.NET Silverlight
Reason #1:
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 application 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 Flash/Flex Testing approaches for Flash/Flex is used.
Win32 Based Applications
There might be several reasons for limited support of Win32 based applications:
420
Contents
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.
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 Settings overview.
Browser (Mozilla Firefox, Google Chrome, Apple Safari, Microsoft Internet Explorer)
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 for more information.
Google Chrome:
UI element identification capabilities for Google Chrome are limited.
Solution:
Please make sure that you have installed and activated the Ranorex Extension in your Google browser. Please refer to
the Google Chrome 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 for more information.
421
Contents
Microsoft Internet Explorer:
UI element identification capabilities for Microsoft Internet Explorer are slow.
Solution:
Please make sure that you have enabled the Ranorex Extension in your Internet Explorer (Manage Add-ons).
Note: The ”Enhanced Protected Mode” needs to be disabled.
Note: The ”Internet Explorer Enhanced Security Configuration” has to be disabled for the add-on to work
on Windows Server machines.
Image Related Automation or Validation
Reason #1:
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 Advanced Settings.
Geometry Related Issues
Reason #1:
Controls 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 Item Properties.
Windows Apps (aka Windows 8 UI Apps)
There are a few reasons causing Windows 8 UI based applications not to be recognized correctly:
Reason #1:
Test execution is started using a Ranorex tool and the setting ’Use UiaLauncher to elevate privileges for processes
started by tools’ (’General Settings’ dialog -> ’Advanced’ tab) is disabled.
Solution:
Enable the mentioned setting.
Reason #2:
Ranorex is not installed in a secure location.
422
Contents
Solution:
Install Ranorex to ’Program Files’ or ’Program Files (x86)’.
Reason #3:
The test executable is not started by a Ranorex Tool.
Solution #1:
Start the test suite using the TestSuiteRunner.
Solution #2:
Use the Ranorex UiaLauncher (\bin\Ranorex.UiaLauncher32.exe) to start the test
executable by passing the executable name as the first argument.
E.g. Ranorex.UiaLauncher32.exe \bin\debug\.exe .
Solution #3:
Add the following lines of code to the Program.cs/Program.vb of the main (executable) project:
C#
if (Ranorex.Core.Util.IsRestartRequiredForWinAppAccess)
return Ranorex.Core.Util.RestartWithUiAccess ();
VB.NET
If Ranorex.Core.Util.IsRestartRequiredForWinAppAccess Then
Return Ranorex.Core.Util.RestartWithUiAccess ()
End If
Reason #4:
You checked the ”Run this program as an administrator” in the Compatibility settings of a Ranorex Tool EXE file,
e.g. for the RanorexStudio.exe file. Setting this option disables access to Windows 8 UI apps.
Solution:
Do not check the mentioned setting for any of the Ranorex EXE files. Alternatively, if you want to always run the tool
using administrator rights, you can create a shortcut to the EXE file and check the ”Run as administrator” option in
the ”Shortcut” -> ”Advanced. . . ” settings of the shortcut properties.
Other Software
Running some antivirus or security software might lead to a limited object recognition with Ranorex tools.
Reason #1:
The antivirus or security software blocks certain Ranorex functionality.
Solution:
Add an exception for the appropriate Ranorex process or temporarily switch off the specific security application.
423
Contents
Different Display DPI Scaling Values
By default, Microsoft Windows is automatically adapting the DPI scaling value for each of your physical displays
connected to your machine. This ensures a uniform experience over all displays, even if the displays have a different
physical size.
When using Ranorex, all physical displays have to be set to the same DPI scaling value.
Solution for Windows 8.1
1. On your Windows 8.1 machine, open the Control Panel and switch to section ’Display’. Do not use the
application ’PC settings’. Make sure the option ’Let me choose one scaling level for all my Displays’ is
checked.
Figure 452
2. After checking this option, choose the size category you prefer.
424
Contents
Figure 453
Press ’Apply’, sign-out and sign-in again to your machine to activate the new settings.
The technology limitation warning should not appear again.
Solution for Windows 10
1. On your Windows 10 machine, open the Windows start menu and choose ’Settings’.
2. Click on ’System’.
425
Contents
Figure 454
3. The section ’Display’ should be shown automatically if not, open it manually. Make sure that all your
physically connected displays have the same setting at ’Change the size of text, apps, and other items’. Move
through the list of displays (labelled with numbers) one by one, and check the setting. When changing a
display value, press ’Apply’ before moving on to the next display.
426
Contents
Figure 455
4. Once all changes have been applied, you can close the ’Settings’ window.
The technology limitation warning should not appear again.
427
Contents
RanoreXPath
A RanoreXPath expression is primarily used to uniquely identify UI elements within a desktop, web or mobile
application. Generally, a RanoreXPath expression consists of:
ˆ Adapters
ˆ Attributes
ˆ and Values
Figure 456: Main components of a RanoreXPath expression
Screencast: A detailed explanation of RanoreXPath expressions, the elements and the way they work can be
found in our screencast named ”RanoreXPath”. You can watch it here: http://youtu.be/UqiCtDlk0hM
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
’Container 1’, which holds a button with text ’Button 1’.
428
Contents
Figure 457: Hierarchical structure of a RanoreXPath
Use the Tracking UI Elements tool to get the RanoreXPath for a particular UI object. To edit a RanoreXPath use
the text box in Ranorex Spy or change the path value of a repository item directly in the repository view. A more
comfortable way to edit RanoreXPath is provided by the The Path Editor.
Note: Use the key in combination with the arrow keys to navigate to the previous or the next
token in RanoreXPath. Use the key and the key in combination with the arrow keys for
selecting specific parts of the RanoreXPath. Use the key in combination with the arrow
key to select the current token of the RanoreXPath (tokens can be a values, identifiers, operators . . . ).
In this section you will learn more about RanoreXPath:
ˆ RanoreXPath Syntax Examples
ˆ Result Set Selector
ˆ Advanced RanoreXPath Example
ˆ RanoreXPath with Regular Expressions
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
/form//button
absolute path identifying all buttons that are descendants of
a form, i.e. all buttons in all levels of a form subtree
429
Contents
.//button
relative path identifying all buttons that are descendants of
the current element (or the element itself), i.e. all buttons
in the subtree of the current element (including the element
itself)
../button
relative path identifying all buttons that are descendants of
the parent of the current element
/form/container?/button
optional location step fitting a container adapter between
form and button; identifies 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 ’Calculator’
/form[@title=’Calculator’ and @instance=’2’]
identifies a top level application with the title ’Calculator’ and
an attribute of instance with value two
/form[@title=’Calculator’ or @class=’SciCalc’]
identifies a top level application with the title ’Calculator’ or
by its class
/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’
/form/button[@text>’sample’] identifies a button with a text attribute starting with ’sample’
/form/button[@text<’sample’] identifies a button with a text attribute ending with ’sample’
/form/button[@text∼’ˆ7’] identifies a button using a RanoreXPath with Regular Expressions
/form/button[@text!∼’ˆ7’] identifies a button not matching a RanoreXPath with Regular
Expressions
/form/control[@items.count=100]
identifies a WinForms control using cascaded attribute names.
The identified control has an ”Items” property that has a
”Count” property which returns the value 100
/form/*[@text=’7’] identifies any element with a text attribute value of ’7’
/form/container?[@caption=’Container 1’]/button
optional location step fitting a container adapter between form and button; identifies both, ’/form/container[@caption=’Container 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
430
Contents
/form/progressbar[@Value>=13.5]
identifies a progress bar with value greater than or equal 13.5
(following comparison operators are also available: >, <=,
<)
/form[@title=$var]
identifies a top level application with title attribute value set
to value stored in variable $var
/form/button[$var]
identifies the button with index equals the value stored in the
variable $var
/dom//input[#’search’]
identifies an input element on a web document with unique
id ’search’ (supported for web testing)
/dom//input[#’search’][@enabled=’True’]
combines the path to a unique id with an additional attribute
(enabled is true)
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 element in the current result list (containing cells only) (Note: the result of the index()-function is
one-based)
/form/table/row/cell[pos()=1]
From the current result list of all element types (everything
beneath the row), the element on the second position will be
identified if it is from type cell (Note: the pos()-function is
zero-based)
/form[x()>100 and y()>100]
identifies a top level application with screen coordinates
greater than 100
/form/button[cx()>10 and cy()>10]
identifies a button with client coordinates (coordinates of an
element relative to its parent) greater than 10
/form[width()>100 and height()>100]
identifies a top level application with width and height greater
than 100
/dom/body/form/button[text()=’Clear’]
If the innertext-attribute is available (web testing), test()
brings back the value of the innertext attribute
/dom/body/form[@id=null()] identifies a form with the id-attribute not being set (=null)
Result Set Selector
Every step in a RanoreXPath expression produces a list containing zero or more elements. These elements can be in
various relationships to each other, for example siblings, parent-child or any other relationship imaginable.
Example: form//button[@enabled=’True’]
The expression above selects all enabled buttons on all available levels below a Form element.
For picking one element from the entire result set, a Result Set Selector can be specified by using an additional set of
brackets.
431
Contents
Example: form//button[@enabled=’True’][2]
From the complete list of enabled buttons (on various levels), the Result Set Selector selects the second element. Note
that the Result Set Selector is only applied after the step where it was specified has been completely evaluated. The
result will be fundamentally different from the result list of the following statement: form//button[@enabled=’True’
and index()=2]
(This would select all enabled buttons with index equal to 2)
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 name (highlighted green)
/table /*/tr/td/a[@InnerText=’Username ’]
2. Select the corresponding checkbox with a relative path from the name (highlighted red)
/../../ td/input[@type=’checkbox ’]
3. Get the full path to the checkbox by combining the two paths.
Figure 458: Advanced RanoreXPath example
RanoreXPath with Regular Expressions
432
Contents
button[@text~’sample[0-9]’]
matches the following button elements: ’sample0’, ’sample1’,
. . . ’sample9’, ’My 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~’^sample123$’]
matches ’sample 123’ (use backslash to escape special characters like space)
listitem[@text~’^(?i:MyTeXt)$’]
matches the regular expression case-insensitive, e.g. ’mytext’,
’MYTEXT’, ’mYTeXT’, . . .
The following are special characters that need to be escaped when used in a regular expression by prefixing 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\.’.
433
Contents
Character 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 ’go*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.
() The parenthesis affects the order of pattern evaluation.
[]
Brackets enclosing a set of characters indicate that any of the enclosed characters may match the
target character.
[^0-9]
The caret immediately following the left-bracket has a different meaning. It is used to exclude
the remaining characters within brackets 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
434
Contents
RanoreXPath Weight Rule Library
ˆ Why RanoreXPath Weight Rules
ˆ How to Add Your Own RanoreXPath Weight Rule
ˆ How to Add Shared RanoreXPath Weight Rules
ˆ Rule Library
Why RanoreXPath Weight Rules
If software is based on dynamic content it is typically based on dynamic identifiers. This might lead to problems in
object recognition as these identifiers will be newly generated every time an element will be displayed.
One way to overcome this challenge is to manually adapt the repository after recording a test scenario which of course
is very time-consuming.
The recommended way of handling dynamic content is to use RanoreXPath Weight Rules to optimize the object
recognition for specific dynamic frameworks.
A path weight rule sets the weight of a specific attribute for a specific capability meeting a set of defined conditions.
The weight will be used when building up the RanoreXPath. The attribute with the highest weight and a value other
than empty will be taken for the identification of the UI element.
The RanoreXPath Weight Rules can be accessed via the ’RanoreXPath Weight Rules’ editor (’Settings -> Advanced
-> Edit Path Weights’ or ’Ranorex Spy -> Edit Path Weights’).
Figure 459: Edit RanoreXPath Weight Rules via settings dialog
435
Contents
Figure 460: Edit RanoreXPath Weight Rules via Ranorex Spy
Using the RanoreXPath Weight Rules can assist you in automatically creating a robust repository which is the base of
a robust test automation framework.
How to Add Your Own RanoreXPath Weight Rule
You can find a detailed description of how to add your own RanoreXPath Weight Rule in the blog post Automated
Testing and Dynamic IDs.
If you want to share your RanoreXPath Weight Rules with the Ranorex community, please send your XML rule to
support@ranorex.com and provide us with a short description.
How to Add Shared RanoreXPath Weight Rules
Open ’RanoreXPath Weight Rules’ editor from settings dialog (Settings -> Advanced -> Edit Path Weights).
Copy the specific XML rule from below ( + , + ) and paste it to ’RanoreXPath Weight
Rules’ Dialog by pressing + or use the context menu.
436
Contents
Figure 461: Add shared rule
Rule Library
RxWinForms ControlNet11 Classnames
XML
name="RxWinForms ControlNet11 Classnames"
enabled="True"
capability="nativewindow"
attribute="class"
setweight="0"
conditionsoperator="and">
source="self"
attribute="class"
match="^WindowsForms10.Window"
negate="False"/>

RxWeb YUI (Yahoo User Interface Library)
XML
name="RxWeb YUI (Yahoo User Interface Library)"
enabled="True"
capability="webelement"
attribute="id"
setweight="0"
conditionsoperator="or">
source="self"
attribute="id"
match="^yui(_\d+)"
negate="False"/>
source="self"
attribute="id"
match="^yui -gen.*"
negate="False"/>

437
Contents
RxWeb JS Frameworks (ExtJS, Sencha, Ozone Widget ,. . . )
XML
name="RxWeb JS Frameworks (ExtJS , Sencha , Ozone Widget ,\dots )"
enabled="True"
capability="webelement"
attribute="id"
setweight="0"
conditionsoperator="or">
source="self"
attribute="id"
match="^ext -.*\d+.*"
negate="False"/>
source="self"
attribute="id"
match="^[a-z]+-\d{4}(-[a-z]*(-\d*)?)?"
negate="False"/>

RxWeb jQuery
XML
name="RxWeb jQuery"
enabled="True"
capability="webelement"
attribute="id"
setweight="0"
conditionsoperator="or">
source="self"
attribute="id"
match="^ui -id -\d+"
negate="False"/>

RxWeb ASP.net
XML
name="RxWeb ASP.net"
enabled="False"
capability="webelement"
attribute="id"
setweight="0"
conditionsoperator="or">
source="self"
attribute="id"
match="^ctl00 (\$textpipe _)(.*(\$textpipe _))"
negate="False"/>

438
Contents
RxWeb GWT
XML
name="RxWeb GWT"
enabled="True"
capability="webelement"
attribute="id"
setweight="0"
conditionsoperator="or">
source="self"
attribute="id"
match="^gwt -uid -\d+.*"
negate="False"/>
source="self"
attribute="id"
match="^isc_.+"
negate="False"/>

RxWeb MS Dynamics CRM
XML
name="RxWeb MS Dynamics CRM"
enabled="True"
capability="webelement"
attribute="id"
setweight="0"
conditionsoperator="or">
source="self"
attribute="id"
match="[a-zA-Z_]+_{([0-9 A-F]+(-)?)+}_\d+"
negate="False"/>

RxWin32 Random ControlIds
XML
name="RxWin32 Random ControlIds"
enabled="False"
capability="nativewindow"
attribute="controlid"
setweight="0"
conditionsoperator="or"/>
439
Contents
Ranorex UI Adapter
When tracking single UI elements with Lesson 9: 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 Lesson 9: 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.
Figure 462: Properties of a Ranorex ’Text’ Adapter
440
Contents
Figure 463: Properties of a Ranorex ’TreeItem’ Adapter
The section ’General’ in Lesson 9: 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#
// Create Text adapter from RanoreXPath
Text textBox = "/form[@controlname=’TestedApp ’]/ text[@controlname=’label3 ’]";
// 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
’ Create Text adapter from RanoreXPath
Dim textBox As Text = "/form[@controlname=’TestedApp ’]/ text[@controlname=’label3 ’]"
’ 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
The following example accesses properties of a Ranorex TreeItem adapter:
C#
441
Contents
// Create TreeItem adapter from RanoreXPath
TreeItem treeItem= "/form[@title=’TreeView Test ’]/?/?/?/ treeitem[@text=’TreeItem ’]";
// Collapse and expand tree item
if (treeItem.Expanded)
treeItem.Collapse ();
else
treeItem.Expand ();
VB.NET
’ Create TreeItem adapter from RanoreXPath
Dim treeItem As TreeItem = "/form[@title=’TreeView Test ’]/?/?/?/ treeitem[@text=’TreeItem ’]"
’ 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 ’Control’. The following
screenshots compare the information shown by Lesson 9: Ranorex Spy for a Win32 and a WinForms button:
442
Contents
Figure 464: Button of calculator application which provides a Ranorex Button and a Ranorex NativeWindow Adapter
443
Contents
Figure 465: Button of a .NET WinForms application which provides an additional Ranorex Control adapter
444
Contents
The Control 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 Control adapter as follows:
C#
// 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 ("BackColor");
VB.NET
’ 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.
445
Contents
Mobile Testing
Learn how to automate Android or iOS app testing for different devices and languages. The following sections will
explain how to set up an environment for mobile testing, how to generate and execute a test and what to do if any
problems occur. The mobile apps KeePassDroid for Android and MiniKeePass for iOS are taken as examples on how
to automate mobile applications using Ranorex.
Introduction
To automate apps on mobile devices (both iOS and Android), these devices need to be connected to a computer with
Ranorex installed. The connection can be accomplished either with a USB cable or over Wi-Fi
Getting Started
To get started with mobile application test automation choose your platform below:
Figure 466
Figure 467
Versioning
Versioning ensures that only versions of the automation library and device service compatible with the currently
installed Ranorex Studio version are used.
When using an incorrect version of an automation library/device service, a warning or error message will be shown.
If you are using an automation library/device service that is still compatible but is not the latest version, you will get
a warning. It is always recommended to use the latest version because it includes the most recent bug fixes, meaning
that you will most probably have the best possible automation experience. If for some reason you have to use an older
library/service version, you can disable the technology limitation warning.
If you are using an incompatible version you will get an error. In this case it is recommended to use the latest version
or at least a compatible one. A version becomes incompatible when completely new features are integrated or the
communication protocol is changed.
Here you’ll find the Mobile Download Archive to download the correct automation libraries matching your Ranorex
version.
For further platform dependent information, have a look at the Android Testing and iOS Testing chapters.
446
Contents
Mobile Download Archive
Please follow the link to the mobile download archive on the Ranorex Website: https://bitly.com/mArchive.
447
Contents
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 and Run an Android Test
Extended Information
After doing your first steps in mobile testing on Android devices please find the following chapters providing detailed
information on more advanced topics and testing scenarios.
ˆ Manage Devices
ˆ Non-UI Testing on Android
ˆ Automation of System Apps
ˆ Run Your Test on Any Android Device
ˆ Testing of Mobile Websites on Android
ˆ Troubleshooting
ˆ Instrumentation with Source Code
ˆ Add Device with Source Code
ˆ Testing of Android Wear Apps
Infrastructure
Before getting started with Android test automation, it’s necessary to choose the connection type that suits your
needs. The following overview helps you to find out which connection type will work best for you.
Record Replay Start/Stop App Install APK Deploy (unattended) Automate System Apps
USB
Wi-Fi
Even if automating via Wi-Fi it is recommended to have your system under test plugged into a power supply during
test recording and execution.
Note: To automate on a device connected via USB instead of Wi-Fi, have a look at ’Add a device connected
via USB’.
448
Contents
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.
Prepare your Android device
In order to ensure that the device connection is as stable as possible, it is recommended to enable the ’Developer
Mode’ on your Android device. This mode grants access to some advanced settings which are responsible for a stable
connection. On Android 4.2 and higher, ’Developer Mode’ is hidden by default. You can unhide it by navigating to
’Settings’ -> ’About Phone’ and tapping ’Build Number’ for seven times. Now return to the previous screen and find
’Developer options’ in the main menu:
Figure 468: Enter ’Developer options’
Inside the ’Developer options’ menu, please enable the following settings:
ˆ ’Stay awake’ which prevents your device from going to Standby during test automation.
Note: Although you might be automating via Wi-Fi, your devices should always be connected to a power
supply to ensure both letting this setting work as well as ensuring to not run out of battery during your
tests. Furthermore it disables any energy saving mechanisms for your Wi-Fi interface and makes the Wi-Fi
connection more stable.
ˆ ’USB debugging’ (only when automating via USB)
449
Contents
Figure 469: Enable ’Stay awake’ and ’USB debugging’
Start your first recording by pressing the record button in Ranorex Recorder.
Next to starting a desktop, web or instant recording it is also possible to start a mobile recording.
Figure 470: Choose technology to record
450
Contents
Figure 471: Record a mobile test
Add Device
Open the ’Manage Device’ dialog by pressing the Devices button from the Record Settings dialog. As we there is no
Android device listed open the ’Add new Device’ dialog by pressing the ’Add’ button.
Choose ’Android’ and follow the instructions to install the Ranorex service on your Android device.
Figure 472: Choose target technology
451
Contents
Figure 473: Choose connection type
Figure 474: Install service app
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.
452
Contents
Figure 475: Installation of the Ranorex Service app
Note: If you have more than one user account activated on your Android device, make sure that the Ranorex
Service app is only installed and running on the owner’s user account.
Note: If you do not have an internet connection on your device, download the Service app from the ”Add
New Device” dialog, connect your device via USB and copy the apk file to the SD card of the device. Open
the copied apk file using a file explorer to install it (Make sure to allow installation of non-Market apps by
enabling ’Settings -> Security -> Device Administration -> Unknown Sources’).
Note: Another possible way to install the service apk is to download the Service app from the ”Add New
Device” dialog, open the command line and switch to the ”Ranorex Android Tools” directory ( Installation Folder>\bin\RxEnv\Android\tools). First of all, type ”adb devices”. If you installed the device’s
USB driver correctly, adb devices should list the connected device properly. Secondly, type ”adb install
/.apk” to install the service app. After performing these steps,
start the installed service app on your device.
After downloading and installing, the Ranorex Service app will be started on the device which can now be added to
the list of devices by selecting your discovered device and clicking on the ’Finish’ button.
453
Contents
Figure 476: Add Android device
If you would like to add an USB connected device, an emulator or if you have problems with a device, have a look at
the Manage Devices and the Troubleshooting section.
Figure 477: 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 - Android.
454
Contents
Note: Note: It’s recommended to fresh instrument your app for every new Ranorex release. For further
information have a look at the section ’Versioning’.
Note: The Instrumentation Wizard can be started from command line. For further details have a look at the
section ’Running Instrumentation Wizard from the Command Line’.
Note: You can also instrument and deploy your APK in a recording or from code. For further details have a
look the chapter ’Types of Action Items’ and the API documentation of the ’InstrumentAndDeployAndroidApp’
method.
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 https://storage.googleapis.com/google-code-archivedownloads/v2/code.google.com/keepassdroid/KeePassDroid-1.99.10.apk.
Next to instrumenting and deploying your Android app, the Instrumentation Wizard allows you to update the Ranorex
Service on your device as well as deploy the RXBrowser app, which enables web testing for Android.
After choosing a device to deploy and an APK file to instrument, the process will be started by pressing the ’Next’
button.
Figure 478: Android Instrumentation Wizard
Note: Open the Advanced Instrumentation Settings dialog by clicking the Advanced button. Here you can
change the APK signing as well as some instrumentation options. When enabling ”Full image comparison”,
a more robust image comparison mechanism will be used. Enabling this option decreases the apps startup
performance but might be useful when having problems with determining resource id’s for images. When
disabling ”Tree simplification”, UI-trees will remain unchanged. This means no post processing will take
place, resulting in larger UI-trees. Disabling this option decreases the apps startup performance but might be
useful when automating 3rd party controls.
455
Contents
After the instrumentation of the APK file, it will be automatically deployed to the selected device.
Figure 479: Successfully finished instrumenting and deploying APK
To finish the instrumentation and deployment process, the installation has to be confirmed on the mobile device.
Figure 480: Confirm installation of instrumented APK
Note: Because the Ranorex automation lib uses non-public API and adds additional permissions to your
APK, make sure you do not release automated APKs to an app store to avoid biased user experience.
456
Contents
Note: If you have problems with instrumenting your APK using the instrumentation wizard or if you want to
integrate the instrumentation into your build process, please have a look at the ”Instrumentation with Source
Code” section.
Record and Run an 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.
Figure 481: Mobile Recording with chosen device and app
By pressing the ’Record’ 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.
Figure 482: Record notification
During the recording process, the action table of the Ranorex Recorder will give a good overview over the performed
457
Contents
steps, as the table is updated live.
Figure 483: 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.
458
Contents
Figure 484: 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.
459
Contents
Figure 485: 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.
Figure 486: Adding actions manually
After recording and adding actions manually, the action table might look something like the following.
460
Contents
Figure 487: Action table
Action #1 is a ’Run Mobile App’ action which starts the instrumented APK file on the selected device.
Note: You can add a launcher activity to your ”Run Mobile App” action by simply adding the activity name to
the ”Startup Arguments” using the following syntax: /
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.
Note: The duration for both, ’Touch’ and ’Long Touch’ can be defined int the properties pane. You can
open this pane by clicking the context menu item ’Properties’ on the ’Touch Event’ action item.
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.
You can use the invoke action to call user defined methods or get and set user defined members. To call such a user
defined method
1. type ’CallMethod’ to the action name field of the invoke action
2. add the method name to the first argument field
3. add a value or a variable you want to pass to the method to the argument field or fields
461
Contents
To get or set a member use ’GetMember’ or ’SetMember’ instead of ’CallMethod’ as action name. For further details
about invoke action have a look at ”Invoking User-Defined Actions”.
User defined methods can also be invoked from code the same way. Here is a short example:
C#
string text = (string) repo.App.Text.Element.InvokeAction("CallMethod", "myCustomGetTextMethod
");
VB.NET
Dim text As String = DirectCast(repo.App.Text.Element.InvokeAction("CallMethod", "
myCustomGetTextMethod"), String)
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 ’Close Application’ action. ’Close Application’ actions stop the selected application on the mobile
device.
Note: Make sure to add a ’Close 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 be stopped by pressing the ’Stop’ button.
Figure 488: 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.
462
Contents
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
ˆ Add an emulator
ˆ Add a device connected via USB
ˆ 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 ’Add new Device’ dialog will be shown. Choose ’Android’ as target technology
and ’Network’ as connection type and follow the instructions to install the Ranorex service on your Android device.
Figure 489: Choose target technology
463
Contents
Figure 490: Choose connection technology
Figure 491: Install service app
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.
464
Contents
Figure 492: Installation of the Ranorex service app
After downloading and installing, the Ranorex Service app will be started on the device which can now be added to
the list of devices by selecting your discovered device and clicking on the ’Finish’ button.
465
Contents
Figure 493: Add Android device
Add a device manually
Add a physical device manually
If a device cannot be found automatically, it can be added by entering name and IP address manually. to do so, click
on the ’The device isn’t listed’ button.
The IP address can be found within the service app on the device by opening the settings.
466
Contents
Figure 494: Ranorex Service app details view
Figure 495: Add mobile device manually
467
Contents
After adding a device, it is available within the ’Manage Devices’ dialog.
Figure 496: 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.
Add an emulator
To add an emulator, choose ’Emulator’ as ’device type/connection’, select the emulator from the list of discovered
devices and set a more readable name.
468
Contents
Figure 497: Choose ’Emulator’
Figure 498: Select the emulator
469
Contents
Figure 499: Set a readable name
Add a device connected via USB
Before adding the device you have to enable USB debugging on your device. Additionally the USB driver has to be
installed. Therefore please refer to the website of the manufacturer of your device. For a detailed description please
have a look at Setting up a Device for Development.
To add an USB device, choose ’USB’ as ’device type/connection’, select the device from the list of discovered devices
and set a more readable name.
Figure 500: Choose USB
470
Contents
Figure 501: Select the USB connected device
Figure 502: Set a readable name
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.
471
Contents
Figure 503: Failed to connect to mobile device
472
Contents
Non-UI Testing on Android
Next to automate testing of the user interface of mobile applications it’s also possible to perform non-UI tests invoking
technology dependent actions (see Types of Action Items). This feature allows you to get information about the
devices hardware, the operating system etc.You are able to get the device info of your Android device directly by
right-clicking the mobile device in Ranorex Spy.
Figure 504: Get device info of Android test device
You can access the non-UI testing methods in the action table by adding an invoke action on the mobile app.
473
Contents
Figure 505: Invoke non-UI testing methods
You can also access the non-UI testing methods within User Code Actions as well as Code Modules.
The code should look something like the following:
C#
var app = repo.AndroidApp.Self.As();
// get an AndroidDeviceInfo object holding all available device info
var info = app.GetDeviceInfo ();
// get a list of SMS from the device
var sms = app.GetSms ();
// get a list of calls from the device
var calls = app.GetCalls ();
// report the manufacturer of the device
Report.Info("Manufacturer: " + info.Manufacturer);
// report the manufacturer of the device
Report.Info("SMS: " + sms.ToString ());
// report the manufacturer of the device
Report.Info("Calls: " + calls.ToString ());
VB.NET
Dim app = repo.AndroidApp.Self.[As](Of AndroidApp)()
’ get an AndroidDeviceInfo object holding all available device info
Dim info = app.GetDeviceInfo ()
’ get a list of SMS from the device
Dim sms = app.GetSms ()
’ get a list of calls from the device
Dim calls = app.GetCalls ()
’ report the manufacturer of the device
Report.Info("Manufacturer: " & info.Manufacturer)
’ report the manufacturer of the device
Report.Info("SMS: " & sms.ToString ())
’ report the manufacturer of the device
Report.Info("Calls: " & calls.ToString ())
474
Contents
For further information about code modules and user code actions please have a look at the sections ”Lesson 7: Code
Modules” and ”User Code Actions”.
475
Contents
Automation of System Apps
When automating an Android App it might sometimes be necessary to leave the application under test. For example
you want to:
ˆ check if an issued notification has been received
ˆ share something on a social network
ˆ change the system settings
As only the application under test is instrumented for Ranorex Automation you can only record within this application.
To automate outside of the application you have to manually create the needed steps using the Ranorex Spy.
Note: To automate system apps the setting ’Android OS Automation’ has to be enabled. The setting can be
found in the mobile section of the plugin specific settings in Plugin Specific Settings.
Note: To speed up the test execution of system app automation you can disable the generation of screenshots
for android. The setting can be found in the mobile section of the plugin specific settings in Plugin Specific
Settings.
476
Contents
Figure 506: Enable Android OS automation
Restrictions
ˆ To automate system apps a USB connection has to be established.
ˆ Highlighting on the device does not work for system apps
ˆ Recording is not possible for system apps
Validate an Issued Notification
The following example will show how to validate a text in a received notification.
Create a new recording and open the Ranorex Spy. You will notice a node labeled ’MobileApp AndroidOS’ at the
application level in the object tree.
477
Contents
Figure 507: System app in Spy
To navigate through the element tree you can either use the tree view. Another way to navigate is to use the
image navigator which can be found at the bottom of the Overview/Advanced tab. Clicking a UI element selects it,
double-clicking outside the selected element selects the parent.
To open the notification bar, a swipe action from the top of the screen has to be performed. Navigate to a tree
element including the navigation bar in the representing screenshot and add this element to the repository using the
context menu.
478
Contents
Figure 508: Add a system app container to the repository
Add a swipe action by dragging/dropping the newly created repository item to the actions table and choosing ’Swipe
Action’ as action type from the context menu.
479
Contents
Figure 509: Add a swipe gesture action
In the properties pane set the swipe direction to ’90’ and the start location to ’0.5;0.0’ which is the top center of the
element.
Figure 510: Set properties of the swipe action
Manually open the notification bar on your device and switch back to Ranorex Spy. Navigate through the element
tree until you’ll find the element you want to validate.
480
Contents
Figure 511: Identify the element to validate
Add the specific element to the repository and add a validation action on the repository item as described before.
Additionally add a key press on the back button to return to the initial situation.
481
Contents
Figure 512: Added validation action
After adding these three actions, the recording is ready to be executed.
482
Contents
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.
Note: Make sure to add a ’Close 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.
Figure 513: 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.
Figure 514: 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.
483
Contents
Figure 515: Open data source dialog. . .
Figure 516: Add a simple data table. . .
484
Contents
Figure 517: And add the device names to the simple data table
After doing so, switch to the ’Data Binding’ tab and bind the data source to the variable in your recording.
485
Contents
Figure 518: Bind the data source to the variable
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.
Figure 519: Successfully executed test on two devices
Run Tests in parallel
It’s also possible to run one test on multiple devices at the same time.
As there is no need to have a data source, disable the previously created data source in the test case properties.
486
Contents
Figure 520: Disable data source
Add a global parameter and bind it to the variable ’varMobileDevice’.
487
Contents
Figure 521: Add global parameter
Figure 522: Bind variable to global parameter
488
Contents
Have a look at ”Lesson 3: Data-Driven Testing” for further details about global parameters and data binding.
In the repository open the RanoreXPath of the mobile app folder using the path editor in Ranorex Spy.
Figure 523: Open advanced RanoreXPath editor
Additional to the title add the device name to the RanoreXPath and choose the variable ’varMobileDevice’ as value.
Figure 524: Add variable device name to RanoreXPath
After performing these steps you can build your test suite and execute the test case from command line using the
command line arguments to set the mobile device name as described in section ”Lesson 4: Ranorex Test Suite Running Tests without Ranorex Studio”:
start MobileTest.exe /pa:globalMobileDevice=”Galaxy Nexus” start MobileTest.exe /pa:globalMobileDevice=”GTP7500”
489
Contents
Testing of Mobile Websites on Android
As described in ”Instrument and Deploy your Android App”, deploy the RXBrowser app to your device using the
Instrumentation Wizard.
Figure 525: Deploy the RXBrowser app to your Android device
You can also download and install the RxBrowser app from our ”Mobile Download Archive” directly to your Android
device by following the link above or by using the following QR code and click on the most recent RxBrowser for
Android.
Figure 526: QR code to the Mobile Download Archive
After performing the mentioned steps it’s possible to access the RXBrowser app as any other instrumented native
Android app from the ’Record a Mobile Test’ dialog. Choose ’Web’ as app and define the website you want to test.
Continue by following the instructions in ”Record and Run an Android Test”.
490
Contents
Note: The Web View in Android 2.3 does face stability problems. Since Ranorex also uses that web view for
Android Web Testing, those instabilities might occur as well.
491
Contents
Troubleshooting
Troubleshooting Android USB connections
ˆ Ranorex cannot find the Android USB connected device
ˆ The USB-Driver cannot be installed (unsigned driver)
Troubleshooting Genymotion
ˆ The Genymotion device cannot be found by Ranorex when trying to add it as emulator
ˆ The Genymotion device cannot be found by Ranorex when trying to add it as emulator)
ˆ The Genymotion device cannot be found by Ranorex when using the USB connection option
ˆ The Genymotion device with installed Ranorex service application cannot be found when using the network
connection option
ˆ The Ranorex RxBrowser gets closed when navigating to the website to automate
For a general troubleshooting please find some General Troubleshooting on connections with Android devices below.
Ranorex cannot find the Android USB connected device
Reason:
Ranorex is using the external ADB (Android Debug Bridge) tool to find all connected USB devices. If the ADB tool is
not able to identify the USB connected devices, also Ranorex won’t be able to do so. To check if a USB connection
can be established, open any ADB tool from the command line (see note below). In the command window type ”adb
devices”. If no device is listed, Ranorex also won’t find the device since no specific USB driver is installed.
Note: The ADB tool can be found in the sub-folder ”Bin\RxEnv\Android\tools” of the Ranorex installation path
(e.g. C:\Program Files (x86)\Ranorex 5.2).
Note: To quickly open up a command window simply keep the SHIFT key pressed while clicking the menu item
”Open command window here” in the context menu of Windows explorer.
492
Contents
Figure 527: List ADB devices from command line
Solution:
First the USB driver for the connected Android device needs to be downloaded. If you are using any Google Nexus
device, please open this website and follow the instructions. For all other devices please visit the manufacturer’s
website and download the USB driver from there. A small list of different manufacturer OEM drivers can be found
here. After downloading the driver please follow instructions here for the installation process.
The USB-Driver cannot be installed (unsigned driver)
Reason and Solution:
For Windows 8 or higher there might be problems with unsigned drivers. Please follow these instructions to disable
the driver signature enforcement. Alternatively any tool can be used that installs the corresponding ADB driver (e.g.
http://adbdriver.com/downloads/) for you.
The Genymotion device does not start
Problem:
Probably there is a problem with the Genymotion VM settings.
Solution:
Please visit the Genymotion FAQ and check whether your issue is described there. Alternatively the following steps
could be done in order to fix the issue with the Genymotion VM settings:
ˆ Delete the VM Host-Only Ethernet Adapter
ˆ Close the Oracle VM and restart Genymotion
493
Contents
The Genymotion device cannot be found by Ranorex when trying to add it as emulator
Reason:
Genymotion is technically an emulator but works differently from Google emulators.
Solution:
Use the USB or Network connection option to add any Genymotion emulator to the Ranorex known device list.
The Genymotion device cannot be found by Ranorex when using the USB connection
option
Reason #1
Genymotion starts his own ADB process allowing to emulate a USB connection. That’s why a Genymotion ADB
process is required.
Solution
Restart the Genymotion emulator and check the Windows Task Manager for the status of the Genymotion ADB
process.
Reason #2
The Genymotion process and the Ranorex ADB process are in conflict with each other.
Solution
First please make sure that Genymotion is running. Continue with opening the Windows Task Manager and with
killing all ADB processes. Please navigate to any ADB tool on your hard disk (see note below) and open a command
window (see another note below) with the current path. Type in ”adb connect ” whereas should be
replaced by the Genymotion Emulators IP address. In order to list all currently available devices, open the Genymotion
Shell and type ”devices show”.
Note: The ADB tool can be found in the sub-folder ”Bin\RxEnv\Android\tools” of the Ranorex installation path
(e.g. C:\Program Files (x86)\Ranorex 5.2).
Note: To quickly open up a command window simply keep the SHIFT key pressed while clicking the menu item
”Open command window here” in the context menu of Windows explorer.
The Genymotion device with installed Ranorex service application cannot be found when
using the network connection option
Reason:
The Genymotion emulator and Ranorex are not running in the same Network.
Solution:
In Genymotion please open the Ranorex Service application. Click on Details so that all available options are shown.
Click on the presented IP address and change it to another one (the one that you are connected with).
494
Contents
The Ranorex RxBrowser gets closed when navigating to the website to automate
Reason:
Some Genymotion emulators have some issues with opening websites. To check whether Genymotion will work
correctly with RxBrowser do the following steps:
1. Start the Genymotion Emulator
2. Start the default Genymotion/Android web browser
3. With the default web browser navigate to the website that you want to automate with RxBrowser
If the website works correctly with the default web browser, then it will also work with RxBrowser. If you face any
issues please find a ”Solution” below.
Solution:
Try another Genymotion emulator or use one of these:
ˆ HTC One X 4.1.1-API16
ˆ Sony Xperia Z 4.3 API18
ˆ Samsung Galaxy S5 4.4.4 API19
General Troubleshooting on connections with Android devices
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.
ˆ If you have more than one network interface configured on your android device, you can switch between them
by touching the IP address in the service app and choosing the desired address.
ˆ 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.
495
Contents
Figure 528: Devices details
ˆ 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.
496
Contents
Figure 529: Set device name
ˆ If you have problems with instrumenting your APK using the instrumentation wizard have a look at the
”Instrumentation with Source Code” section.
497
Contents
Instrumentation with Source Code
Note: Note: It’s recommended to fresh instrument your app for every new Ranorex release. For further
information have a look at the section ’Versioning’.
1. Link the Ranorex JAR library to your android project. You can find the Ranorex.jar file in your Ranorex
installation directory: \bin\RxEnv\Android\Ranorex.jar
2. Manually add following code to all your Activities:
Java
@Override
public void onResume ()
{
super.onResume ();
com.ranorex.android.RanorexAndroidAutomation.Hook(this);
}
@Override
public void onPause ()
{
super.onPause ();
com.ranorex.android.RanorexAndroidAutomation.UnHook(this);
}
@Override
public boolean dispatchKeyEvent(android.view.KeyEvent event)
{
com.ranorex.android.RanorexAndroidAutomation.Key(event);
return super.dispatchKeyEvent(event);
}
3. Add permissions to your manifest file (if not already in place):
XML


4. In your AndroidManifest.xml under the application node add:
XML


with the corresponding Ranorex and automation library version.
498
Contents
Add Device with Source Code
ˆ Add a using directive to Ranorex.Core.Remoting
C#
using Ranorex.Core.Remoting;
VB.NET
Imports Ranorex.Core.Remoting
ˆ Add the following code to add a device connected via Wi-Fi and start the first Ranorex instrumented app found
on the device:
C#
var device = RemoteServiceLocator.Service.AddDevice(
"DeviceName",
RemotePlatform.Android ,
RemoteConnectionType.WLAN ,
"IPAddress");
device.WaitFor(ChannelState.DeviceConnected);
var firstApp = device.RanorexCompatibleApps [0];
device.StartApplication(firstApp);
device.WaitFor(ChannelState.AppConnected);
VB.NET
Dim device = RemoteServiceLocator.Service.AddDevice(
"DeviceName",
RemotePlatform.Android ,
RemoteConnectionType.WLAN ,
"IPAddress")
Choose a proper device name and set the IP address of your device when using a network connection.
When using a USB connection set the remote connection type to RemoteConnectionType.USB instead of
RemoteConnectionType.WLAN and the serial of the device instead of the IP address.
499
Contents
Testing of Android Wear Apps
Following the instructions below you can easily create automated tests on compatible Android Wear apps directly on
real or emulated devices.
Prerequisites
ˆ Install adb: The Android Debug Bridge (adb) is a versatile command line tool that lets you communicate with an emulator instance or connected Android device. You can find it at folder>\Bin\RxEnv\Android\tools.
ˆ Connect with the phone: Download the Android Wear app on your phone and pair the watch with your phone.
You can find detailed information on how to do so here: https://support.google.com/androidwear#topic=6056405
ˆ Enable the debug mode: On the smartphone go to ”Developer Options” and enable ”USB Debugging”. On
the watch got to ”Developer Options” and enable ”ADB Debugging” as well as ”Debug over Bluetooth”.
ˆ Finally, open the Android Wear app on your smartphone, press the Settings button on the top right and check
the ”Debugging over Bluetooth”. The target should be shown as connected.
Note: If the target is still disconnected, try to restart both the smartphone and the watch.
Getting Started
Connect the device via USB to your computer and call adb via command line by typing ”adb devices”.
It should print something like this: List of devices attached 08937p69d0518aac device
This means you have successfully connected your phone to your computer. Now we need to connect the watch too.
Type the following commands: adb forward tcp:6666 localabstract:/adb-hub adb connect localhost:6666
Note: You need to accept the connection on your watch.
Type once again ”adb devices”. You should now see a new device called localhost:6666: 08937p69d0518aac
device localhost:6666 device
In your Android Wear App, Host and Target should now show up as connected.
Note: Connecting host and target does not always work at first go. Try restarting both devices in different
order and be patient.
Now you can Add Device, Instrument and Deploy your Android App and Record and Run an Android Test.
Automate on an Emulated Device
The following instructions explain how to connect a Genymotion emulated smartphone with a Google emulated watch.
500
Contents
First, download Genymotion setup and start any Genymotion emulator with Android 4.3 or later. For Google’s
emulated watch you need the AVD Manager.
Start the Android Studio, go to Tools -> Android -> AVD Manager. Create a new Virtual Wear device and start it.
Next, install Google Apps or Gapps on the Genymotion smartphone. With Gapps, also the Play Store will be installed,
which is needed for downloading the Wear App.
Go to http://wiki.cyanogenmod.org/w/Google Apps and download the correct Gapps for your emulator. To install
Gapps on Genymotion, please follow these instructions.
Note: Gapps may sometimes be unstable when running on Genymotion emulators.
Follow the steps explained in Prerequisites and list your devices via adb as described in Getting Started.
It should print something like this:List of devices attached 192.168.154.102:5555 device
This means you have successfully connected your emulated phone to your computer. Now you need to connect the
watch too. Type the following command into the command line:adb -s {genimotion ip}:{genimotion port} -d forward
tcp:5601 tcp:5601
Type once again the ”adb devices” command. You should see a new device called emulator-5600.
You can now Add Device, Instrument and Deploy your Android App and Record and Run an Android Test.
501
Contents
iOS Testing
Learn how to automate your iOS app testing for different iPhone/iPad devices and languages. The following sections
will explain how to set up an environment for iOS testing, how to generate and execute a test and what to do if any
problems occur. The iPhone/iPad app MiniKeePass is taken as an example of mobile application automation using
Ranorex.
ˆ Infrastructure
ˆ Getting Started
ˆ Record and Run an iOS Test
Extended Information
After doing your first steps in mobile testing on iOS devices please find the following chapters providing detailed
information on more advanced topics and testing scenarios.
ˆ Instrumentation and Preparation
ˆ iOS Service App
ˆ Non-UI Testing on iOS
ˆ Run a Test on Any iOS Device
ˆ Testing of Mobile Websites on iOS
ˆ Instrumentation with Source Code on iOS
Infrastructure
Before getting started with iOS test automation, it’s necessary to choose the connection type that suites your needs.
The following overview helps you to find out which connection type will work best for you.
Record Replay Start/Stop App Install IPA Deploy (unattended)
USB
Wi-Fi
Note: To make an iOS app testable with Ranorex, it is necessary to instrument the app. However, for a
quick start you can take your first steps with the pre-instrumented KeePass app (see Getting Started) that is
provided for download.
USB Requirements
iTunes is necessary to establish a USB connection (debug mode and non-debug mode) because iTunes installs the
USB driver on the Windows machine to connect to iOS devices.
502
Contents
Network Requirements
When choosing ”Wi-Fi” as connection type, it is recommended that you have your system under test plugged into a
power supply during test recording and execution. Additionally make sure that the system under test (the mobile
devices) and the machine running the tests (where Ranorex is installed) are on the same network.
Getting Started
Although at the end of the day you might want to test your own mobile application, you can also take your first steps
with the pre-instrumented MiniKeePass app. Please scan the QR code with your device and follow the link to the
mobile download archive. From there the app can easily be installed.
Figure 530: QR code for the mobile download archive
Note: In order to automate your own mobile app it needs to be instrumented guided by the instructions in
the section Instrumentation and Preparation.
The following steps are needed to get started with the sample application:
1. Connect your iOS device (Wi-Fi or USB). See Infrastructure for pros and cons.
2. Go to the mobile download archive on your device using the QR Code above or the url bitly.com/mArchive.
3. Download and install the iOS service app and make sure it is started on your device.
4. Download and install the sample app and initially start it to let the service app recognize it.
5. Add the device in Ranorex using the Device Wizard. You’ll find more details in the section Adding Your iOS
Device
6. Start your mobile recording
Note: There is a small sample delivered with Ranorex Studio (can be found on the start page) that shows
how the iOS MiniKeePass app can easily be tested with Ranorex.
503
Contents
Record and Run an iOS Test
After preparing the device and instrumenting the app, the recording can be started by choosing the device on which
the test should be executed and the app to be tested.
Figure 531: Mobile recording with chosen target technology. . .
Figure 532: . . . device and app
By pressing the ’Record’ button, a notification on the desktop will inform you, that actions will be recorded directly
on the mobile device.
504
Contents
Figure 533: Record notification
During the recording process, the action table of the Ranorex Recorder will give a good overview of the steps performed
as the table is updated live.
505
Contents
Figure 534: Action table updates during recording process
During recording, it is possible to add validations using the Validation button. By pressing this button, a dialog will
open where the element which is to be validated can be selected.
506
Contents
Figure 535: Select element to validate
After choosing an element, the ’Validate Element’ dialog will pop up. In this dialog, the attributes to be validated can
be selected.
507
Contents
Figure 536: Choose attribute to validate
In addition to recording actions directly, it is also possible to add actions to the action table at a later time. This can
be done by dragging a repository item to the action table and choosing the action which should be performed from
the menu.
508
Contents
Figure 537: Adding actions manually
If your device is connected via USB you can also add a ’Deploy iOS App’ action to automatically deploy the current
version of your application under test for each test run. Choose the device, the file location of the app archive and
the app id to enable automated deployment.
Figure 538: Add ’Deploy iOS App’ action
After recording and adding actions manually, the action table might look something like the following.
509
Contents
Figure 539: Action table
Action #1 is a ’Deploy iOS App’ action which deploys the given app to the selected device.
Action #2 is a ’Run Mobile App’ action which resets the instrumented app on the selected device.
Action #3 is a Touch Event on a button. There are two 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 can be compared to a right click.
Note: The duration for both ’Touch’ and ’Long Touch’ can be defined in the properties pane. You can open
this pane by clicking the context menu item ’Properties’ on the ’Touch Event’ action item.
Action #4 is a ’Set Value’ action, which is typically used for keyboard input.
Action #5 is a ’Mobile Key Press’ action. With a ’Mobile Key Press’ action you can simulate the ’Enter’ button on
your devices keyboard.
Action #6 is a ’Wait For Not Exists’ action, which is useful for cases where an item indicates a loading process and
the automation should continue after the item has disappeared.
Action #7 is a ’Validate’ action as was previously described.
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 an ’Invoke Action’ which performs a scroll action on a table control to its index ’0’. Invoke actions
directly call the corresponding method of the selected adapter.
You can use the invoke action to call user-defined methods or get and set user-defined members. To call such a
user-defined method
1. Type ’CallMethod’ into the action name field of the invoke action
2. Add the method name to the first argument field
3. In the following argument field enter a value or choose a variable you want to pass to the method
4. Repeat the previous step for all additional arguments
510
Contents
To get or set a member, use ’GetMember’ or ’SetMember’ instead of ’CallMethod’ as the action name. For further
details about invoke action, have a look at Invoking User-Defined Actions.
User-defined methods can also be invoked from code in the same way. Here is a short example:
C#
string text = (string) repo.App.Text.Element.InvokeAction("CallMethod", "myCustomGetTextMethod
");
VB.NET
Dim text As String = DirectCast(repo.App.Text.Element.InvokeAction("CallMethod", "
myCustomGetTextMethod"), String)
Action #11 is a ’Close Application’ action. ’Close Application’ actions stop the selected application on the mobile
device.
Stop Recording
After performing the test on the mobile device, the recording process can be stopped by pressing the ’Stop’ button.
Figure 540: 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.
511
Contents
Instrumentation and Preparation
This quick starting guide will show you, how to prepare your iOS project before creating the application package (IPA
file) and how to Instrument and Deploy iOS applications using Ranorex Studio.
Prepare your iOS device
It’s recommended to disable the ’Auto-Lock’ functionality during your test executions. To do this, open the Settings
app, tap the ’General’ settings, choose ’Auto-Lock’ settings and set ’Auto-Lock’ to ’Never’.
Figure 541: Disable Auto-Lock
Prepare Your iOS Project Before Creating the IPA File
In order to ensure that the instrumentation and deploying will work correctly, it is recommended to do the steps
described below.
ˆ Make sure that no Ranorex libs are linked to the project.
Note: Ranorex studio cannot instrument iOS applications, which have been already instrumented with Xcode
using the Ranorex libs.
ˆ The iOS Deployment target should be correctly set.
512
Contents
Note: If the Deployment target doesn’t match, between the iOS device and the iOS application, Ranorex
Studio will show you an error message that will tell you why the application could not be deployed.
Figure 542: Correctly set the deployment target
ˆ Make sure that the Architecture (armv7 or arm64) match with the iOS device, which will be used for testing.
Obtaining the P12 Certificate and the Mobile Provisioning Profile
All iOS applications must be correctly signed with P12 certificate and matching provisioning profile.
Because the instrumentation will make some changes to the application package (IPA file), the application must be
signed again.
Note: For more information about signing and distribution, refer to the official Apple documentation.
To obtain the P12 certificate, perform the following steps:
ˆ Open the Keychain Access tool on your Mac machine.
ˆ Under the Category section, select My Certificates.
513
Contents
Figure 543: Export the certificate
ˆ Make a right mouse click on your certificate and choose Export.
ˆ Type a password and save the certificate.
Figure 544: Enter password
Note: Make sure that you have chosen a valid Developer certificate.
The mobile provisioning profile can be obtained with Xcode or on the iOS Dev Center website.
If you are using Xcode, perform the following steps:
ˆ In Xcode menu choose Xcode and select the Preferences option.
ˆ Select your Apple ID and choose View Details
514
Contents
Figure 545: Select your Apple ID
ˆ In Signing Identities choose iOS Development
ˆ With the right mouse click select your Provisioning Profile and choose Show in Finder
515
Contents
Figure 546: Show profile file in finder
ˆ Copy the Provisioning Profile to your windows machine
If you are using the iOS dev center website, please make the following steps:
ˆ Navigate to https://developer.apple.com/devcenter/ios/index.action
ˆ Log with your developer account
ˆ Go to Member Center
ˆ Go to Certificates, Identifiers & Profiles
ˆ Choose Provisioning Profiles
ˆ Download your Provisioning Profile
516
Contents
Figure 547: Download provisioning profile
Note: The development provisioning profile should be used for testing your app and not the distribution
provisioning profile.
Adding Your iOS Device
Note: When using Wi-Fi as the connection type, make sure that your iOS device or simulator is reachable
over Wi-Fi.
Start your first recording by pressing the Record button in Ranorex Recorder.
Next to starting a desktop, web or instant recording it is also possible to start a mobile recording.
Open the ’Manage Device’ dialog by pressing the ’Add device’ button in the Record Settings dialog.
Figure 548: Choose technology to record
517
Contents
Figure 549: Record a mobile test
Choose ’iOS (iPhone, iPad)’ and follow the instructions to install the service app on your device shown in the following
dialog.
Figure 550: Choose ’iOS’
518
Contents
Figure 551: Install service app
Make sure that the service app is running on your device.
Choose the preferred connection type.
Figure 552: Choose connection type
When choosing USB as the connection type, the connected device should be discovered automatically. Choose the
device from the list to finish the process.
519
Contents
Figure 553: Add new device
If the device cannot be found automatically click the ”The device isn’t listed” button.
Enter the name of the device and choose the corresponding device serial.
Figure 554: Add device manually
When choosing Wi-Fi as the connection type the device should be visible in the list of devices. Choose the device to
add it to your list of devices.
If the device cannot be found automatically, click the ”The device isn’t listed” button.
Enter a name and IP address of the device and click ”Finish” to add the device manually.
520
Contents
Figure 555: Manually adding device
Figure 556: Added iOS device
Instrument and Deploy Your iOS Application Package
Apart from Instrumentation with Source Code on iOS the recommended way is to instrument iOS application packages
(IPA files) with Ranorex Studio on a Windows machine.
Note: Note: It’s recommended to fresh instrument your app for every new Ranorex release. For further
information have a look at the section ’Versioning’.
521
Contents
After setting up the iOS device, the app which should be automated has to be instrumented and deployed to the
device. The Instrumentation wizard for instrumenting and deploying an IPA file can be started from ’Manage Devices’
dialog or directly by starting the instrumentation wizard as described in the section iOS.
Figure 557: iOS instrumentation wizard
Before instrumenting any IPA file, the iOS signing must be configured first. To do so, press Settings button in the
Instrumentation wizard for iOS. In the iOS instrumentation Settings dialog choose your P12 certificate, type the
correct password and choose the mobile provisioning profile. To get the P12 certificate and mobile provisioning
profile, please read the chapter Obtaining the P12 Certificate and the Mobile Provisioning Profile.
522
Contents
Figure 558: Instrumentation settings
After choosing an iOS USB connected device to deploy and an IPA file to instrument, the process will be started by
pressing the ’Next’ button.
523
Contents
Non-UI Testing on iOS
In addition to automating testing of the user interface of mobile applications, it’s also possible to perform non-UI
tests invoking technology-dependent actions (see Types of Action Items).
This feature allows you to get information about the devices hardware, the operating system etc.
To enable this feature you have to additionally link the library Mobile Download Archive as well as the following
libraries:
ˆ AVFoundation.framework
ˆ CoreTelephony.framework
ˆ SystemConfiguration.framework
ˆ ExternalAccessory.framework
Now you are able to get the info on your iOS device directly by right-clicking the mobile device in Ranorex Spy.
Figure 559: Get device info on an iOS test device
You can access the device information during your test automation within User Code Actions as well as Code Modules.
The code should look something like the following:
C#
var app = repo.iOSApp.Self.As ();
// get an iOSDeviceInfo object holding all available device info
524
Contents
var info = app.GetDeviceInfo ();
// Report e.g. the IP address of the device
Report.Info("IP address: " + info.IpAddress);
VB.NET
Dim app = repo.iOSApp.Self.[As](Of IosApp)()
’ get an iOSDeviceInfo object holding all available device info
Dim info = app.GetDeviceInfo ()
’ Report e.g. the IP address of the device
Report.Info("IP address: " & Convert.ToString(info.IpAddress))
For further information about code modules and user code actions please have a look at the sections ”Lesson 7: Code
Modules” and ”User Code Actions”.
525
Contents
iOS Service App
This quick starting guide will show you, how to properly use the new iOS RxServiceApp to create automated tests
and how to prepare your iOS project so that start/stop app functionality can be used.
Prepare Your iOS Project to Enable Start/Stop Functionality
Note: The following step by step instructions are based on Xcode 6.
If the app will be instrumented manually, please do the following steps to register the custom URL scheme so that
the starting and stopping will work correctly:
ˆ Open your project in Xcode 6.x
ˆ Follow the instructions in the section Instrumentation with Source Code on iOS
ˆ In Xcode choose the ”Info” tab
ˆ Under Custome iOS Target Properties add URL types key
ˆ Expand URL types key with Item0
ˆ Expand Item0 with URL schemes
ˆ Expand URL schemes with Item0 and write the app activity name as value
Figure 560: Enable start/stop functionality
Note: If no URL scheme is set, the app under test cannot be launched and you will get an error message
when you try to start the app with Ranorex. In the app list of the iOS RxServiceApp there will be also a
warning message ”Can’t launch”.
ˆ After Instrumenting and deploying the app for the first time, start the app manually once.
526
Contents
Note: The newly instrumented and deployed app, needs to be started manually for the first time, so that it
gets registered at the RxServiceApp.
Note: If the app is instrumented with Ranorex Studio on the Windows machine, the correct URL scheme will
be set automatically.
Proper use of the iOS Service App
To use the new start/stop functionality via USB or WiFi, make sure that the RxServiceApp is running and is active
on the device. You can either use the instrumentation wizard to deploy the service app as described in ”iOS”, or
download and install the service app on your device from our mobile download archive by scanning the following QR
Code or the using the following short URL:
Figure 561: Use the QR Code above or the url
bitly.com/mArchive to
directly access the download archive on your mobile device.
Note: Start/Stop functionality can not be used from the home screen of the device, even if the RxServiceApp
is running in the background.
You can still create automated tests without the iOS RxServiceApp. Please note that without the RxServiceApp the
start/stop functionality won’t work.
To add a device without the service app, make sure that an instrumented app is running and active on the device.
Note: When using the start functionality, the app under test will be launched multiple times, because it
needs to be reseted into initial state.
527
Contents
Note: If you want to create automated test on an instrumented app that has no URL Scheme, please make
sure, that the RxServiceApp is not installed on the device and that the testing app is active on the device.
528
Contents
Run a Test on Any iOS Device
We will show you how easy it is to run your iOS test on any iOS device. To do so, add a second device as described
earlier.First convert the ’Device Display Name’ value of the ’Run Mobile App’ action in a recording variable.
Figure 562: Make the device name value variable
After making the device name value variable, open the ’Data Source’ dialog of the test case with your recording and
add a new simple data table containing the names of the devices on which you want to run the test on.
529
Contents
Figure 563: Add a simple data table
Figure 564: Add the device names to the simple data table
530
Contents
After doing so, switch to the ’Data Binding’ tab and bind the data source to the variable in your recording.
Figure 565: Bind the data source to the variable
See Lesson 3: Data-Driven Testing if you want to learn more about the data-driven approach to testing.The test suite
is now prepared for running the recording on different devices. After successfully running the test, the test report
should look like the figure below.
531
Contents
Figure 566: Successfully executed test on two devices
Note: If you want to run one test on multiple devices at the same time, have a look at the section ’Run
Tests in parallel’.
532
Contents
Testing of Mobile Websites on iOS
If you are going to automate web testing on your iOS device or simulator, you can use our already instrumented
RxBrowser app.
You can either directly install the app onto your device (recommended method) or manually deploy it to from
Xcode to your device.
For the first approach either use the instrumentation wizard where you can find the option Install Ranorex Browser as
described in ”iOS”, or open the ”Mobile Download Archive” on your iOS device by following the link above or by
using the following QR code and clicking on the RxBrowser distributable.
Figure 567: QR code for the Mobile Download Archive
For the second approach follow the description below:
ˆ Download and extract the RxBrowser Xcode project (RxBrowser.zip) from the ”Mobile Download Archive” to
your Mac.
ˆ Open the unpacked project with Xcode.
ˆ Clean and build the project.
ˆ Either deploy the app from Xcode to the device or create an IPA file to deploy it from a Windows machine to
the device.
533
Contents
Figure 568: Build and deploy the project to your iOS device or simulator
After performing the steps above, it’s possible to access the RxBrowser app just like any other instrumented native
iOS app. Continue by following the instructions in the ’Adding Your iOS Device’ section.
534
Contents
Instrumentation with Source Code on iOS
Instrument and Deploy your iOS app
First you have to instrument your iOS app.
Note: Note: It’s recommended to fresh instrument your app for every new Ranorex release. For further
information have a look at the section ’Versioning’.
This can be done by either following along with the video instructions or by following the textual description below.
Figure 569: Opening XCode project and add a new target
Figure 570: Adding the necessary libraries to the XCode project
535
Contents
Figure 571: Modifying linker flags and building a project.
ˆ Download the automation lib from the ”Mobile Download Archive” on your Mac.
Note: The file size of Ranorex Automation Library is about 30 megabytes. This doesn’t automatically make
your app 30 megabytes bigger, since it is a universal library and only the parts essential for your app will
dynamically be added when compiling it.
ˆ Open the XCode project of your application under test.
Figure 572: Open *.xcodeproj file
ˆ In order to avoid shipping an instrumented app to your customers it is recommended to create a separate target
for your app under test. You should select the project file and duplicate the existing target.
536
Contents
Figure 573: Duplicate Target
ˆ Rename the newly created target.
Figure 574: Rename duplicated target
Note: As XCode does not automatically update all necessary files, you have to rename them manually.
You will have to alter the target itself, the targets .plist file (in workspace as well as in Build Settings
-> Packaging), the targets’ project name (Build Settings -> Packaging) and the schemes name (Product
-> Manage Schemes).
ˆ Add the previously downloaded automation lib to your newly created target.
537
Contents
Figure 575: Add new file to project
538
Contents
Figure 576: Choose the lib file and specify the target, i.e. where the lib will be added
539
Contents
ˆ After doing this, the automation lib will be listed in the ’Linked Binary With Libraries’ list in the ’Build Phases’
pane of the test target.
Figure 577: Added automation library
ˆ Add the CFNetwork framework to the list.
540
Contents
Figure 578: Add CFNetwork.framework
Figure 579: Added automation lib and network framework
541
Contents
Note: With iOS 8.3 you additionally have to add the IOKit.framework.
ˆ In the ’Build Settings’ pane of the test, add the switches ’-ObjC -all load’ to the option ’Other Linker Flags’.
Figure 580: Set the switches ’-ObjC’ and ’-all load’
After performing these steps, your project can be built using the newly created target and scheme for your iOS devices
as well as simulators.
Note: If you see the debug output ’RxAutomationEngine init’ in the console pane, your app has been
instrumented successfully.
Figure 581: Successfully instrumented app
Note: Because the Ranorex automation lib uses non-public APIs, make sure that you do not submit a
Ranorex instrumented app to the app store as your app might be rejected and you might be banned from
submitting apps to the app store for a period of time.
542
Contents
Note: To add your device via Wi-Fi, it’s necessary that the application under test is started on your iOS
device or simulator.
Note: The development provisioning profile should be used for testing your app and not the distribution
provisioning profile.
Note: To improve the object recognition of your app under test set the accessibility label attribute of your
controls.
543
Contents
Web Testing
The Ranorex Web Plugins (for Microsoft Internet Explorer, Mozilla Firefox, Google Chrome 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
ˆ Find or filter Web Elements
ˆ Cross-Browser Testing
ˆ Recordings & Repositories
ˆ 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
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.
Figure 582: Representation of websites
544
Contents
Figure 583: RanoreXPath example
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#
// 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();");
VB.NET
’ 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();")
545
Contents
Find or filter Web Elements
The Ranorex Framework offers a wide range of adapters for each HTML tag elements (e.g.: ATag adapter for
tags). Each adapter has specific methods and attributes; the link tag () for example has additional attributes
like HREF, TARGET and REL.
C#
// 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
’ 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 Instrumentation Wizard. Creating
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#
// 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 ’]";
546
Contents
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
’ 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
Lesson 5: 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 repositorycontains all required UI web element objects used within the
actions table.
547
Contents
Figure 584: Web based recording
Repositories and the WebDocument
The following example shows how to access the methods of the WebDocument using a repository:
C#
// 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
’ 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 ()
548
Contents
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:
http://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)
Figure 585: Ranorex Web Testing reference page
Handling of AJAX
C#
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";
549
Contents
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();
// Wait for the ajax request for max 10 seconds (10000 milliseconds)
PreTag result = webDocument.FindSingle(".// div[@id=’ajax_response ’]/div/pre", 10000);
VB.NET
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#
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","#33 ff00");
}
Report.Info(rowInfo);
}
550
Contents
VB.NET
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", "#33 ff00")
Next
Report.Info(rowInfo)
Next
Set inputs, tag attributes and perform a click without mouse
C#
// 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 = "
VB.NET
’ 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 = "
Execute javascript code
C#
webDocument.ExecuteScript("history.back();");
VB.NET
webDocument.ExecuteScript("history.back();")
Handling of layer menus
C#
WebDocument webDocument = "/dom[@caption=’Ranorex Test Page ’]";
DivTag topMenuDiv = webDocument.FindSingle(".// div[@id=’top -menu ’]");
// Bring the main menu to the front
551
Contents
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
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
552
Contents
Source Control
Introduction to Source Control
A source control system, also called revision control or version control system (VCS), keeps track of changes to a file
or set of files. One can thus see who made changes and when. It allows reverting single files, or an entire project, to
a previous state and comparing changes over time. It provides an easy way to recover previous versions of a file or
project.
There are two types of version control systems: centralized version control systems, such as Subversion and Team
Foundation Version Control, and distributed version control systems like Git.
Important notice
This User Guide section provides information on the software prerequisites for each of the supported version control
systems and how they can be used within Ranorex Studio.
As a precondition we assume you have knowledge about version control in general, as well as your specific version
control system. Setting up and configuring the version control system of your choice is not in the scope of this
documentation.
Source Control in Ranorex Studio
Ranorex Studio supports three version control systems. You can find more details on how to connect Ranorex Studio
with these version control systems in the corresponding chapters:
ˆ Git
ˆ Subversion
ˆ Microsoft Team Foundation Server (TFVC)
553
Contents
Git
Using Git for Source Control
ˆ About Git and Ranorex Studio
ˆ Add a Ranorex Solution to Git
ˆ Check out a Ranorex Solution from Git
ˆ Icon overlays in Projects View
About Git and Ranorex Studio
Git is a distributed version control system which is free and open source.
In order to use Git as a source control provider in Ranorex Studio, the following preconditions have to be fulfilled in
the given order:
ˆ Git needs to be installed Download Git for Windows here: https://git-scm.com/download/win Please make
sure you choose to ’Use Git from the Windows Command Prompt’ during Git installation!
Figure 586
554
Contents
ˆ TortoiseGit needs to be installed Download TortoiseGit here: https://tortoisegit.org/download TortoiseGit
is a Windows shell interface to Git and is needed, for example, to overlay icons which show the file status.
Ranorex Studio will assist you with this dialog in case the required prerequisite is not present on the machine:
Figure 587
Add a Ranorex Solution to Git
Please make sure your Git infrastructure is set up and working.
To add an existing Ranorex Solution to Git, open the context menu of the solution. Go to ’Source Control’ and
select ’Add Solution to Source Control’.
555
Contents
Figure 588
To add a new Ranorex Solution to Git, check the option ’Add to Source Control’ in the ’New Project’ dialog.
556
Contents
Figure 589
The ’Source Control Wizard’ will be opened. Please follow these instructions:
1. Choose ’Git’ as Source Control provider.
557
Contents
Figure 590
2. The Ranorex Solution is automatically configured as a new local Git repository. All files are indicated with a
plus sign in Projects View.
558
Contents
Figure 591
3. To commit the current state to the local repository click on ’Commit. . . ’ in the context menu of the solution.
559
Contents
Figure 592
560
Contents
4. After the commit a check symbol is shown in Projects View.
Figure 593
All further Git related steps should be defined in your workflow.
Check out a Ranorex Solution from Git
Please make sure your Git infrastructure is set up and working.
1. Open the ’Tools’ menu, move to ’Source Control’ and click on ’Checkout’.
561
Contents
Figure 594
2. Choose ’Git’ as Source Control provider in Source Control Wizard.
562
Contents
Figure 595
3. TortoiseGit will ask you for the path to the repository and where you would like to store the files on your local
machine. Fill in the URL to the Git repository as well as the path to the local directory and press ’OK’.
563
Contents
Figure 596
4. The whole repository will be cloned to the local folder. After a successful clone this dialog will be shown.
564
Contents
Figure 597
5. In case your repository includes a Ranorex Solution in its root, this solution will be opened automatically. If
this is not the case, you have to open the Ranorex Solution manually from the file System. After opening the
Ranorex Solution from the local folder you see the icon overlays in Projects View.
565
Contents
Figure 598
All further Git related steps should be defined in your workflow.
Icon overlays in Projects View
Overlay icons are added to the items in the Projects View in Ranorex Studio, as the solution is under source control.
Icon overlays
Normal Not locally modified, no changes waiting for commit.
Conflicted Indicates a conflict.
Modified Modified, changes are waiting to be committed.
Added Marked for addition, waiting to be committed.
566
Contents
Subversion
Using Subversion for Source Control
ˆ About Subversion and Ranorex Studio
ˆ Add a Ranorex Solution to Subversion
ˆ Check out a Ranorex Solution from Subversion
ˆ Icon overlays in Projects View
ˆ Options
ˆ Using another version of SharpSvn and TortoiseSVN
About Subversion and Ranorex Studio
Subversion is a centralized version control system by Apache (https://subversion.apache.org/ ).
To get more information about Subversion, please have a look at the official Subversion online documentation:
http://svnbook.org
Ranorex Studio uses two applications for working with subversion, which are installed with Ranorex Studio by default:
ˆ SharpSvn Is a set of libraries for working with Subversion.
ˆ TortoiseSVN It is a Windows shell extension for Subversion and provides the icon overlays showing the file
status in Ranorex Studio.
Ranorex Studio will assist you with this dialog in case the required prerequisite is not present on the machine:
Figure 599
Add a Ranorex Solution to Subversion
Please make sure your Subversion infrastructure is set up and working.
To add anexisting Ranorex Solution to Subversion, open the context menu of the solution. Go to ’Source Control’
and click on ’Add Solution to Source Control’.
567
Contents
Figure 600
To add a new Ranorex Solution to Subversion, check the option ’Add to Source Control’ in the ’New Project’
dialog.
568
Contents
Figure 601
The ’Source Control Wizard’ will be opened.
Please follow these instructions:
1. Choose ’Subversion’ as Source Control provider.
569
Contents
Figure 602
2. TortoiseSVN will ask for the URL of the repository.
Figure 603
3. Authenticate yourself on the subversion server.
570
Contents
Figure 604
4. Choose the folder in the repository you want to add your solution to.
571
Contents
Figure 605
5. Check the files you want to have under source control and uncheck the files you don’t want to have under
source control respectively.
572
Contents
Figure 606
6. The chosen files will be added to source control.
573
Contents
Figure 607
7. Now, commit the changes to the Subversion server.
574
Contents
Figure 608
8. The commit is done.
575
Contents
Figure 609
After performing these steps, your solution is under source control and your local copy is up to date.
Figure 610
Check out a Ranorex Solution from Subversion
Please make sure your Subversion infrastructure is set up and working.
1. Open ’Tools’ menu, move to ’Source Control’ and click on ’Checkout’.
576
Contents
Figure 611
2. Choose ’Subversion’ as Source Control provider in Source Control Wizard.
577
Contents
Figure 612
3. Enter the URL of your repository and specify the checkout directory.
578
Contents
Figure 613
4. The chosen project will be checked out.
579
Contents
Figure 614
Icon overlays in Projects View
Overlay icons are added to the items in the Projects View in Ranorex Studio, as the solution is under source control.
Icon overlays
Normal Not locally modified, no changes waiting for commit.
Conflicted Indicates a conflict.
Modified Modified, changes are waiting to be committed.
Added Marked for addition, waiting to be committed.
Options
In Ranorex Studio Options you can find options related to Subversion.
Open main menu item ’Tools’ and choose ’Options’. In the following dialog select folder ’Tools’ and sub-item
’Subversion Options’. By default, all checkboxes are checked. The currently used SharpSvn version can be found here.
580
Contents
Figure 615
Using another version of SharpSvn and TortoiseSVN
In order to use another version of TortoiseSVN and SharpSvn than the preinstalled ones, you have to download and
install the version you want to use:
ˆ Download and install TortoiseSVN first from http://tortoisesvn.tigris.org/.
ˆ After that download, the corresponding package for SharpSvn from https://sharpsvn.open.collab.net. Please
make sure you choose the right version of SharpSvn, which matches the TortoiseSVN version.
ˆ Extract the downloaded Version.
ˆ Copy the extracted folder to ’\RanorexStudio\AddIns\SourceControl\SubversionAddin’.
ˆ Once you restart Ranorex Studio, the correct version of SharpSVN will be automatically chosen.
581
Contents
Team Foundation Version Control (TFVC)
Using Team Foundation Version Control (TFVC) for Source Control
ˆ About Team Foundation Version Control (TFVC) and Ranorex Studio
ˆ Add a Ranorex Solution to TFVC
ˆ Check out a Ranorex Solution from TFVC
ˆ Icon overlays in Projects View
ˆ Options
About Team Foundation Version Control (TFVC) and Ranorex Studio
Team Foundation Version Control (TFVC) is a centralized version control system by Microsoft included in Team
Foundation Server.
In order to work with TFVC in Ranorex Studio either Microsoft Visual Studio or Team Explorer for Microsoft Visual
Studio have to be installed on the same machine. These programs come with the required ’Team Foundation Server
MSSCCI Provider’.
Ranorex Studio will assist you with this dialog in case the required prerequisite is not present on the machine:
Figure 616
The MSSCCI interface supports single byte character sets (SBCS) only. Here you can find a description on how to
change the code page. This means there is no MBCS support.
Add a Ranorex Solution to TFVC
Please make sure your Team Foundation Server infrastructure is set up and working.
582
Contents
For adding anexisting Ranorex Solution to TFVC open the context menu of the solution. Go to ’Source Control’
and click on ’Add Solution to Source Control’.
Figure 617
To add a new Ranorex Solution right from the beginning to TFVC check the option ’Add to Source Control’ in the
’New Project’ dialog.
583
Contents
Figure 618
The ’Source Control Wizard’ will be opened.
Please follow these instructions:
1. Choose ’Microsoft Team Foundation Server’ as Source Control provider.
584
Contents
Figure 619
2. Select your Team Foundation Server.
585
Contents
Figure 620
3. Choose the folder you want to add your solution to.
586
Contents
Figure 621
587
Contents
4. Select the files you want to have under source control and deselect the files you don’t want to have under
source control respectively and perform a check in.
Figure 622
After performing these steps, your solution is under source control and your local copy is up to date.
588
Contents
Figure 623
Check out a Ranorex Solution from TFVC
Please make sure your Team Foundation Server infrastructure is set up and working.
1. Open ’Tools’ menu, move to ’Source Control’ and click on ’Checkout’.
Figure 624
2. Choose ’Microsoft Team Foundation Server’ as Source Control provider in Source Control Wizard.
589
Contents
Figure 625
3. Specify the local check out Directory
590
Contents
Figure 626
4. Select your Team Foundation Server.
Figure 627
5. Choose the folder in the repository you want to check out from server.
591
Contents
Figure 628
592
Contents
6. The chosen solution will be checked out.
Icon overlays in Projects View
Overlay icons are added to the items in the Projects view in Ranorex Studio as the solution is under source control.
Icon overlays
Checked In File under source control, not checked out for editing.
Checked out File under source control, checked out, not dirty.
Checked out Modified File under source control, checked out, dirty.
Added File added to project, not checked in.
Options
In Ranorex Studio Options you can find options related to TFVC.
Open main menu item ’Tools’ and choose ’Options’. In the following dialog select folder ’Tools’ and sub-item ’TFS
Options’. By default, all checkboxes are checked.
If you are working with TFVC and running into performance problems with big solutions, uncheck ’Enable file state
’Modified’ check’.
593
Contents
Figure 629
594
Contents
Integration
Introduction
Ranorex can perfectly be used as a standalone tool in order to launch automated tests manually on local and/or
remote machines. However it might be more powerful and comprehensive to integrate Ranorex with other tools.
These tools could be Continuous Integration (CI) tools, Test Management (TM) tools or simply with Task Scheduling
tools. This comes with the main benefit that automated tests get launched automatically. This launch could be
triggered by a specific action (e.g. source code commit from a developer), a periodical build (e.g. ”nightly build”), a
test case with underlying test automation or simply triggered by a scheduled task for a specific (e.g. every midnight).
Figure 630
Continuous Integration
There are a lot of brilliant and useful Continuous Integration tools around. See how to integrate Ranorex into a
typical Continuous Integration process which is explained in detail in our general blog post:
Integrate Ranorex into Any Continuous Integration Process
For several widely spread Continuous Integration tools please find the a specific blog post here:
ˆ Jenkins: Integrating Ranorex Automation in Jenkins CI Process
ˆ Bamboo: Bamboo CI with Ranorex Test Automation
ˆ TeamCity: Integrating Ranorex Automation in TeamCity CI Process
For a deeper integration of your Ranorex Report into a common CI tool (e.g. Jenkins) using xUnit/jUnit please see
the blog post:
Fully integrate your Ranorex Report with CI tools like Jenkins using xUnit
595
Contents
This blog post also contains explanations and downloadable samples for the XSL transformation of the Ranorex report
to xUnit/jUnit format.
Test Management and Application Lifecycle tools
Nowadays Test Management (TM) tools and Application Lifecycle Management tools (ALM) are more and more
important. They store the information how testing is organized, implemented, and executed as well as a clearly
arranged history of executed tests from the past.
There is a lot of excellent tool support. For the integration of Ranorex into two widely spread test management tools
and ALM tools respectively please read the blog posts:
ˆ Running Ranorex Automated Tests with HP Quality Center
ˆ Running Ranorex Automated Tests with Microsoft Test Manager
Although Coded UI Tests as well as VAPI-XP tests might be specific for the particular tool, the common idea of
integrating Ranorex with TM/ALM tools might be pretty much the same for all other tools around. It all breaks
down to the usage of command line arguments for tailored automated test runs with Ranorex.
Team Foundation Server
There is a comprehensive article about the Microsoft Team Foundation Server, Visual Studio and Microsoft Testmanager
and the Integration with Ranorex. Please find the documentation here:
TFS 2012 and Ranorex
Atlassian Jira
There is a very informative blog post on how to integrate Ranorex Test Cases into the issue and defect management
tool Jira. Please find it here:
ˆ Integrating Ranorex Test Cases into Jira
Source Control / Revision Control
Integration can also be accomplished with Ranorex Studio - namely integrating Source Control tools. First and
foremost it should be mentioned that any common Source Control tool can be used to control relevant files of a
Ranorex Studio Solution - which are text-based files only.
There is a specific integration of two of these tools, namely for SVN (Subversion) and TFS (Team Foundation Server).
Please find detailed information on the source control integration and support here: Source Control.
596
Contents
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:
ˆ Create
ˆ Build
ˆ Run
ˆ Adding New Items
ˆ Solution Explorer
ˆ Debugging
ˆ Code Completion
ˆ Code Conversion
ˆ Code Navigation
ˆ Code Generation
ˆ Refactoring
597
Contents
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.
Figure 631: ’New Project’ dialog
Ranorex Test Suite
A project holding a Ranorex Test Suite which may contain recordings and
code modules. This might be your first choice when starting with Ranorex
Studio
Ranorex Test Suite Module Library A project holding recordings and code modules which can be shared and
reused
Ranorex Class Library A project for creating classes which are used in other applications
Ranorex Console 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.
598
Contents
Figure 632: Ranorex Studio
599
Contents
Build
After creating your application, it can be built using the ’Build’ menu.
Figure 633: ’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.
Figure 634: ’Output’ window
Build Errors and Warnings will be displayed in the ’Errors’ window.
Figure 635: ’Errors’ window
Project specific settings can be defined in the ’Project Options’ dialog, which can be accessed from the ’Project’
menu.
600
Contents
Figure 636: Opening ’Project Options’ menu 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.
Figure 637: ’Project Options’ ’Application’ tab
You can also set the target CPU and framework or the output path in the ’Compiling’ tab.
601
Contents
Figure 638: ’Project Options’ ’Compiling’ tab
602
Contents
Run
After building the project successfully, it can be executed from the ’Debug’ menu either with or without debugger.
Figure 639: ’Debug’ menu
603
Contents
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.
Figure 640: Add new item through ’Project’ menu
604
Contents
Figure 641: Adding new item through ’Project Explorer’ context menu
Figure 642: ’New File’ dialog
605
Contents
Additional to Ranorex specific files as
ˆ Code Module,
ˆ Module Groups,
ˆ Recording Module and
ˆ Repository
programming language specific files like
ˆ Class,
ˆ 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 Community Blog.
606
Contents
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.
Figure 643: 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.
607
Contents
Figure 644: Delete file from project
It’s also possible to redefine the ’Start Up Project’ of a solution.
608
Contents
Figure 645: Set project as StartUp project
609
Contents
Debugging
Ranorex provides the possibility to debug code directly in the development environment.
To enable the debugger press the ’Enable Debugging’ button in the toolbar.
Figure 646: Enable Debugging
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
Figure 647: Add breakpoint
ˆ by putting the cursor to the line you want to add a breakpoint, open the ’Debug’ menu an choose ’Toggle
Breakpoint’.
610
Contents
Figure 648: 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:
Continue Debugging Continues 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
611
Contents
Figure 649: Debugging menu Items
Figure 650: Debugging toolbar items
To skip several lines of code and continue debugging on a specific line, the context menu item ’Set Current Statement’
can be chosen by right-clicking on the line and choosing ’Set Current Statement’ from the context menu.
612
Contents
Figure 651: 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.
613
Contents
Figure 652: Debug sub menu
Callstack Shows method calls currently on stack.
Local Variables Shows variables defined in the function currently being executed, arguments passed into the
current function and fields and properties of the class where the function is defined.
Watch
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 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.
614
Contents
Figure 653: Tool tip
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.
615
Contents
Code Completion
Ranorex supports code completion as you type.
Figure 654: Code Completion in Ranorex
Further details about how this works can be found in the article Code Completion posted at SharpDevelop Community
Blog.
616
Contents
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 ’Convert’ from
the context menu.
Figure 655: Convert the whole project from C# to VB.NET
617
Contents
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 Code Navigation posted at SharpDevelop Community Blog.
618
Contents
Code Generation
Ranorex Studio can help you saving time with providing you auto generated code and code templates as described in
the article Code Generation posted at SharpDevelop Community Blog.
619
Contents
Refactoring
Ranorex Studio supports several mechanisms to refactor code. Further details can be found in the article Refactoring
posted at SharpDevelop Community Blog.
620
Contents
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 Calculator.
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. Choose another language if you would like to implement Ranorex
code in VB.NET or Visual C++.
Figure 656: 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 Core’ and all ’Ranorex Plugin’-References.
621
Contents
Figure 657: Add new references . . .
Figure 658: . . . 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#
using System.Drawing;
using Ranorex;
VB.NET
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#
[STAThread]
static int Main(string [] args)
622
Contents
VB.NET
_
Public Shared Function Main(args As String ()) As Integer
Add the following code lines to the ’Main’ routine of the class ’Program’:
C#
int error = 0;
try
{
System.Diagnostics.Process pr = System.Diagnostics.Process.Start("calc.exe");
Form form = Host.Local.FindSingle ("form[@processname=’"+pr.ProcessName+"’]"
);
form.Activate ();
Button button = form.FindSingle (".// button[@controlid =’132’]");
button.Click();
button = form.FindSingle (".// button[@controlid =’92’]");
button.Click();
button = form.FindSingle (".// button[@controlid =’133’]");
button.Click();
button = form.FindSingle (".// button[@controlid =’121’]");
button.Click();
}
catch (RanorexException e)
{
Console.WriteLine(e.ToString ());
error = -1;
}
return error;
VB.NET
Dim returnError As Integer = 0
Try
Dim pr As System.Diagnostics.Process = System.Diagnostics.Process.Start("calc.exe")
Dim form As Form = Host.Local.FindSingle(Of Ranorex.Form)("form[@processname=’" & pr.
ProcessName & " ’]")
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.
623
Contents
System Requirements
The following system requirements are valid for all Ranorex components including Studio, Runtime, Spy, Recorder,
License Manager and Agent.
ˆ Supported Operating Systems
ˆ Software Requirements
ˆ Hardware Requirements
ˆ Required Disk Space
Firewall Configuration
ˆ Ranorex License Manager Firewall Configuration
ˆ Ranorex Agent Firewall Configuration
Former Ranorex Versions (up to 6.0)
ˆ System Requirements for Ranorex Versions up to 6.0
Supported Operating Systems
Ranorex supports the following operating systems (32- and 64-bit editions, except for Itanium-based systems):
ˆ Windows XP
ˆ Windows Vista
ˆ Windows 7
ˆ Windows 8
ˆ Windows 8.1
ˆ Windows 10
ˆ Windows Server 2003
ˆ Windows Server 2003 R2
ˆ Windows Server 2008
ˆ Windows Server 2008 R2
ˆ Windows Server 2012
ˆ Windows Server 2012 R2
624
Contents
Software Requirements
The following software requirements are needed to run all Ranorex components (Runtime, Spy, Recorder, License
Manager and Agent). They are usually automatically installed when running the Ranorex setup:
ˆ Microsoft Windows Installer 3.1 or higher
ˆ Microsoft Visual C++ 2008 x86
ˆ Microsoft Visual C++ 2008 x64 (required for 64 bit Windows versions only)
ˆ Microsoft Visual C++ 2010 x86
ˆ Microsoft Visual C++ 2010 x64 (required for 64 bit Windows versions only)
ˆ Microsoft Visual C++ 2015 x86
ˆ Microsoft .NET Framework 4.0 or higher
ˆ Internet Explorer 7 or higher (with the latest patches and updates)
Hardware Requirements
The hardware requirements depend on the .NET Framework version that needs to be installed for the respective
Ranorex package. Ranorex (Runtime, Spy, Recorder, License Manager, Studio and Remote Agent) requires the
installation of the .NET Framework 4.0 or higher. The minimum system requirements for running Ranorex
(Runtime, Spy, Recorder, License Manager, Studio and Agent) are the same as those for the .NET Framework
4.0: https://www.microsoft.com/en-US/download/details.aspx?id=17718
The recommended minimum system requirements for running Ranorex (Runtime, Spy, Recorder, License Manager,
Studio and Remote Agent) are:
ˆ Processor: 2 GHz
ˆ Memory: 512 MB
Required Disk Space
ˆ Full installation: Approximately 200 megabytes (MB) free disk space are required to install the full Ranorex
package (includes Ranorex Studio, main components, documentation, etc.).
ˆ Minimum installation: Approximately 80 megabytes (MB) free disk space are needed to install the Ranorex
runtime environment.
ˆ Ranorex Agent: A Ranorex Agent requires approximately 25 megabytes (MB) free disk space. Please keep in
mind that a Ranorex Runtime License is needed per Ranorex Agent.
Ranorex License Manager Firewall Configuration
On a system running Ranorex License Manager, the firewall must be configured to allow access to TCP and UDP
port 7266.
625
Contents
Ranorex Agent Firewall Configuration
On a system running a Ranorex Agent, the firewall must be configured to allow access to TCP ports 8081 and 29189,
and UDP ports 10000-10001.
System Requirements for Ranorex Versions up to 6.0
Software Requirements
The following software requirements are needed to run all Ranorex components (Runtime, Spy, Recorder, License
Manager). They are usually automatically installed when running the Ranorex setup:
ˆ Microsoft Windows Installer 3.1 or higher
ˆ Microsoft Visual C++ 2008 x86
ˆ Microsoft Visual C++ 2008 x64 (required for 64 bit Windows versions only)
ˆ Microsoft Visual C++ 2010 x86
ˆ Microsoft Visual C++ 2010 x64 (required for 64 bit Windows versions only)
ˆ Microsoft .NET Framework 2.0 SP2 or higher
ˆ Internet Explorer 7 or higher (with the latest patches and updates)
Additionally, for automating WPF applications (since Ranorex 5.3) and running Ranorex Studio the following
prerequisites are required:
ˆ Microsoft .NET Framework 3.5 SP1 or higher
Hardware Requirements
The hardware requirements depend on the .NET Framework version that needs to be installed for the respective
Ranorex package. Ranorex (Runtime, Spy, Recorder, License Server) requires the installation of the .NET Framework
2.0 or higher. Ranorex Studio requires the .NET Framework 3.5. Consequently: 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 recommended minimum system requirements for running Ranorex (Runtime, Spy, Recorder, License Server):
ˆ Processor: 2 GHz
ˆ Memory: 512 MB
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
The recommended minimum system requirements for running Ranorex Studio:
ˆ Processor: 2 GHz Dual Core
ˆ Memory: 1 GB
Required Disk Space
ˆ Full installation: Approximately 200 megabytes (MB) free disk space are required to install the full Ranorex
package (includes Ranorex Studio, main components, documentation, etc.)
626
Contents
ˆ Minimum installation: Approximately 80 megabytes (MB) free disk space are needed to install the Ranorex
runtime environment.
627
Contents
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.
Note: 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’ or ’(32 bit)’ in the Windows Task Manager, all others use
the 64 bit architecture.
Figure 659: Task manager showing 64 and 32 bit calculator 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).
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 ’Compiling’ tab in the project properties. .NET applications are by
default started as 64 bit processes on 64 bit operating systems unless the target CPU is explicitly set to the 32 bit
(x86) architecture. Consequently, set the ’Target CPU’ property to ’Any processor’ for automating 64 bit applications
and to ’32-bit Intel-compatible processor’ for 32 bit applications.
Figure 660: Ranorex Studio - advanced compiler settings
628
Contents
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 Close or Minimize the RDP Window
ˆ Disable Mouse/Keyboard Activities
ˆ Use same Color and Resolution Settings
ˆ Increase Timeouts on Virtual Machines
ˆ Keeping remote session unlocked even if closing it
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. Consequently, 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 Console 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
629
Contents
C#
Keyboard.Enabled = false;
and
C#
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#
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. Consequently 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.
Keeping remote session unlocked even if closing it
There is a way to keep the remote session unlocked even if you’ve disconnected the RDP session.
Find out more here: How do I make sure that my user session keeps unlocked if I close my remote session?
630
Contents
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 Command Line Arguments
ˆ Install Ranorex License
Installation Packages
Ranorex uses the Microsoft/Windows Installer (MSI) for its setup. Consequently, 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 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
The silent installation will not work for any prerequisites (a message will pop-up asking whether you want to install the
required components) due to legal limitations. If you want to make sure that all System Requirements are installed
silently as well, you need to install them separately, e.g. using a batch file.
If you do not want to install all Ranorex features, you can (de)select these features using the command line options
’ADDLOCAL’ 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: Ranorexx.x.x.exe ADDLOCAL=”ALL” REMOVE=”RanorexStudioFeature”
Possible feature names used as parameter to ADDLOCAL or REMOVE (separated by commas) are:
ˆ ’MainFeature’ (Core components)
ˆ ’RanorexSamples’
ˆ ’RanorexStudioFeature’
ˆ ’RanorexFirefoxExtension’
ˆ ’RanorexIEAddon’
ˆ ’RanorexDocumentation’
631
Contents
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 would like to install afloating license you have to copy the file Ranorex3 Server.lic (for Ranorex3.x installations)
or Ranorex2 Server.lic (for Ranorex 2.x installations) into the folder ’%ALLUSERSPROFILE%’ by using the ’XCOPY’
command in a batch file. The file will be created when you first install a License Server license on a Ranorex Client.
Just search for that file on a client machine running a floating license.
If you would 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 Ranorex3.x installations) or Ranorex2.lic (for Ranorex 2.x installations) and copy it to the folder
’%ALLUSERSPROFILE%’ by using the ’XCOPY’ command in a batch file.
632
Contents
XCOPY Deployment
Running tests without Ranorex Installation
Opening Note: The way of deploying tests without Ranorex Installation described below is possible but
not recommended. Still this approach is documented since it allows to overcome internal policies and/or
restrictions inhibiting installations on runtime environments, e.g. due to group policies within domains.
Deploy Ranorex Libraries and Assemblies
The required files for executing Ranorex tests on runtime machines are located in the ”bin” folder of the Ranorex
installation path. These files can be found easily on machines having a valid Ranorex Installation using the environment
variable %RANOREXPATH%. Please copy the whole content of the ”bin” folder (including all subdirectories) to a
target folder () on the runtime machine.
xcopy ”%RANOREXPATH%\bin\*.*” xcopy
Note: It is crucial to deploy the Ranorex Assemblies with exactly the same version that was used to compile
the test executable
Deploy Ranorex License Information
In the runtime environment a valid license information needs to be available. Most likely the runtime machine will use
a floating license, so the only information necessary can be provided by the license file (Ranorex3 Server.lic). This file
can be copied easily from any machine having a floating license installed to the target machine and is located in the
path of the environment variable %ALLUSERSPROFILE%. For more information please refer to chapter ”Install
Ranorex License” in the section ”Silent Installation of Ranorex”.
Deploy Your Ranorex Test
Ranorex generates the files needed to run automated tests in the ”Output Folder” (by default\bin\Debug)
of a test suite project.
633
Contents
Figure 661: Open output folder from Ranorex Studio
634
Contents
Note: You can directly access this folder by right-clicking the current project and choosing ”Open Output
Folder” in the context menu.
Next to files needed for test execution, additional files are created in the output folder during test execution (e.g.
Reports, Screenshots etc.). Those files do not have to be copied. It’s recommended to clear your output folder before
and then trigger a new build (Build -> ”Build Solution” or hot key F8).
Required files for executing Ranorex test automation:
ˆ Executable file (*.exe)
ˆ Test Suite File (*.rxtst)
Additionally required on the base of your project needs:
ˆ Ranorex Module Group (*.rxtmg), only necessary if modules groups are in use
ˆ Test Data (*.xlsx, *.xlsb, *.xls, *.csv, *), only necessary for data driven tests and if data source files were added
to project
ˆ Module Libraries (*.dll), only necessary if module libraries are linked and embedded functionality is referenced
in the Test Suite
ˆ Sub folder ”RepositoryImages” including all files, if exists
Finally copy the files needed to the target machine and place them in the folder where all Ranorex Libraries and Assemblies are already located (). Of course, by copying the whole output folder (”bin\debug” by default),
you will ensure you have everything possibly required for running your test. xcopy ”\bin\debug\*.*”
xcopy
Note: For executables being explicitly compiled against 64bit CPUs, place these files in the sub folder ”x64”
of the target folder.
635
Contents
Licensing
In general Ranorex provides two different types of licenses to install:
ˆ Installing a Node Locked License
ˆ Installing a Floating 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.
If you are going to transfer a license to another machine, have a look at the section Transfer Licenses.
License Registration
In order to register a Ranorex license, start the Ranorex Licensing tool, which is available in the Ranorex start menu
folder.
Figure 662: 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 ’Node-Locked’ 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 has been delivered to you by email and press ’Install’.
636
Contents
Figure 663: Installed license after activation
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.
Figure 664: Error Dialog - ’No internet connection available’
The web site address 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.
637
Contents
Figure 665: License authentication using Ranorex web site
Installing a Floating License
Installing and configuring the Ranorex License Manager
In order to use a Ranorex Floating License it is required to install and run the Ranorex license manager application on
a computer within a network. The download link for the license manager 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 manager and client, it is required
to open port 7266 for TCP and UDP access on the machine running the license manager.
Note: By installing a Ranorex license manager it’s required to use a Ranorex license manager installation
package at least as current as your Ranorex client installation.
Note: The Ranorex license manager can be used in IPv4, IPv6 and mixed networks.
638
Contents
Figure 666: License manager dialog - one premium licenses in use
Open the Ranorex license manager configuration tool. Add the floating license keys to the text box and press ’Install’.
These licenses are now ready to use.
To get more information about the clients leasing a license you can select the specific license in license manager
configuration tool and open the ’Clients’ tab.
Using the ’Save Log’ button allows you to export all actions processed by the license manager as CSV- or XML-file
for further processing.
Note: It is recommended to have an internet connection available in order to install a new license.
Figure 667: 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 address 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.
639
Contents
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 ’Floating’.
Figure 668: Using license manager for automatically requesting an appropriate license
Press the button ’Detect’ to request a list of the currently available license managers within the local network.
The license type specifies which license (Runtime, Premium) should be used on the client. By selecting ’Auto’, the
client automatically requests the appropriate license. In case of running Ranorex tests via the standalone test suite
runner or from command line, only a Runtime floating license will be used. When starting Ranorex Spy tool a Premium
floating license will be leased on the manager. 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
manager. If the type of the required license is available, it will be assigned to the requesting client. By being idle,
closing Ranorex Studio or finishing a test run the license will be automatically released and can then be used by other
clients.
For this reason a reliable network environment is required when working with floating licenses.
Note: If a floating license has not been released correctly (based on a network problem for example), it will
be locked for a time-out of 5 minutes.
Uninstall License
In order to uninstall a floating license right-click the license you are going to uninstall and choose ”Uninstall License(s)”
from the context menu in the Ranorex license manager tool.
640
Contents
Figure 669: Uninstall floating license
Figure 670: Confirm uninstall
In order to uninstall a node-locked license from a machine, please use the uninstall button in the Ranorex License
Tool.
641
Contents
Figure 671: Uninstall node-locked license
Figure 672: Confirm uninstall
Transfer Licenses
In order to transfer a license, you have to uninstall the license from the machine you want to transfer it from as
described in the section above. After that, the license will be available for installation on a different machine.
642
Contents
How to instructions
This library includes instructions for often needed tasks in a short and practical format:
ˆ How to create a Ranorex Snapshot
ˆ How to create a compressed Ranorex solution
ˆ How to create a compressed Ranorex Report
ˆ How to add a solution settings file to a solution
643
Contents
How to add a solution settings file to a solution
What is a solution settings file?
A solution can have one solution settings file, named ’Ranorex.rxsettings’. It stores the value of so called solution
settings in it. Find out more about solution settings here: Solution settings
Add a solution settings file to a solution
1. Start Ranorex Studio.
2. Load the solution.
3. Click on ”Create solution settings” in the toolbar of the ’Projects’ view.
Figure 673
4. A folder named ’Solution Items’, including the solution settings file ’Ranorex.rxsettings’ is automatically created.
Figure 674
644
Contents
How to create a Ranorex Snapshot
What is a Ranorex Snapshot?
A Ranorex Snapshot is a representation of the the user Interface (UI) structure of a system under test (SUT) at a
particular Point in time. A Ranorex Snapshot captures all interface elements, their hierarchy, values, etc.
It can be saved as a single file. A Ranorex Snapshot file can be created and viewed with Ranorex Spy. The file
extension is ’.rxsnp’.
Typically, Ranorex Snapshots are used to share detailed information about the UI of a SUT with the Ranorex Support
and Technical Sales Team.
Create a Ranorex Snapshot
1. Start your system under test (SUT).
2. Start Ranorex Spy.
3. Get to the part of your SUT you want to create a snapshot of.
4. In Ranorex Spy, press the TRACK-Button.
Figure 675
If you move the mouse cursor over a UI element, a red border will appear around this element in tracking mode.
5. Place the mouse cursor over the UI element of the SUT you want to track. Wait until the red border appears
and left click your mouse button.
6. The tracked element automatically appears in Ranorex Spy.
7. Click on ’Save as Snapshot. . . ’ in Ranorex Spy toolbar, select the desired location, enter a filename and click
’Save’.
645
Contents
Figure 676
8. A progress dialog is shown during snapshot creation.
646
Contents
Figure 677
Wait until the snapshot is created and successfully saved to the file.
647
Contents
Figure 678
Snapshots of special UI elements
Particular UI elements of the SUT, such as drop-down menus, pop-up windows, combo boxes, etc., only become
visible after a mouse click, or disappear if the SUT loses focus. These elements are often not automatically included
in a Ranorex Snapshot , as they appear as separate items in Ranorex Spy at the top level of the element tree.
There are two ways to create Ranorex Snapshots of these elements:
Temporarily deactivate tracking with F12 key
1. Start your SUT.
2. Start Ranorex Spy.
3. Get to the part of your SUT you want to create a snapshot of.
4. In Ranorex Spy, press the TRACK-Button.
Figure 679
Now you are in tracking mode, which is indicated by a red border around the UI elements as you move the
mouse cursor over them.
648
Contents
5. Press and hold F12 key while navigating to the desired element in the SUT. While you press the F12 key, the
tracking mode is paused.
6. Move the mouse over the UI element of the SUT you want to track and release the F12 key.
7. Wait until the red border appears and press the Scroll key. A temporary Ranorex Snapshot is created in Ranorex
Spy. This may take a few seconds.
8. Save the Ranorex Snapshot as described above.
Instant capturing with key shortcut Ctrl + Win
1. Start your SUT.
2. Start Ranorex Spy.
3. Get to the part of your SUT you want to create a snapshot of.
4. Place the mouse cursor above the part of the SUT you want to create a Ranorex Snapshot of and press key
shortcut Ctrl + Win. This instantly tracks the element in Ranorex Spy.
5. Save the Ranorex Snapshot as described above.
649
Contents
How to create a compressed Ranorex solution
What is a compressed Ranorex solution?
A compressed Ranorex solution is a file archive including all relevant files of a solution.
Create a compressed Ranorex solution
1. Start Ranorex Studio.
2. Load your solution.
3. In the Ranorex Studio menu click on Tools > Zip Solution. The zip-file will be created in the folder of the
solution.
Figure 680
4. A Windows Explorer opens, showing you the final zip-file.
Figure 681
650
Contents
How to create a compressed Ranorex Report
What is a compressed Ranorex Report?
A compressed Ranorex Report is one single file including all files that belong to a single report. These are the report
file itself (*.rxlog), all images and further relevant files. The file extension is ’.rxzlog’.
Create a compressed Ranorex Report
1. Open a Ranorex Report in Ranorex Studio or with Ranorex Report Viewer.
2. Open the context menu with a right mouse click on the report and choose ’Save As. . . ’.
Figure 682
3. Select the desired location, enter a filename and make sure ’Ranorex Compressed Report (*.rxzlog) is selected
as file type.
Figure 683
651
Contents
4. Click ’Save’
652
Contents
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?
ˆ How can I speed up my Excel-based data connector?
ˆ 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?
ˆ Can I run my tests on machines where I am not allowed to install Ranorex?
ˆ Can 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?
ˆ Are there known incompatibilities with other software?
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
(see Lesson 6: UI Mapping with Ranorex 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. Code
Examples
653
Contents
Does Ranorex support data driven testing?
Yes. Ranorex supports four different data connectors to build data driven test cases:
ˆ Simple Data Table
ˆ SQL Connector
ˆ CSV File
ˆ Excel File
A general description of how to create data driven test cases can be found here:
Lesson 3: Data-Driven Testing
How can I speed up my Excel-based data connector?
Especially with big files, the performance of Microsoft’s default file format for excel spreadsheets is getting poor. This
weakness might also affect your data driven test execution. For performance improvements you could use the binary
file format (xlsb) instead of the default one (xlsx). Simply save your Excel spreadsheet with the extension ”xlsb” and
assign it to your Excel File.
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 Waiting
for UI Elements - Repository Timeouts 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.
Check 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. Compare
the absolute path, shown within the object repository’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 how to use user code actions in recordings here:
User Code 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, CheckBox, Text, ListItem, TreeItem,
. . . ). You can only create a Button Adapter of an element if the element supports the Button role, i.e. if Ranorex
Spy 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.
654
Contents
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 run my tests on machines where I am not allowed to install Ranorex?
Yes, it is possible to run automated tests on runtime machines without Ranorex Installation. Please refer to the
chapter XCOPY Deployment (Running tests without Ranorex Installation) in the User Guide.
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. Visual Studio Integration
What shall I do with unexpected dialogs and popup windows during test
automation?
Ranorex provides the dedicated class ”PopupWatcher” to watch for and to handle popup windows. By using this
class, not only simply click actions to close popup dialogs can be called. Even more complex scenarios can be handled
in custom callback routines being called at the time the popup appears.
Read more about how to handle popup dialogs with Ranorex in the section Handling unexpected Dialogs.
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
Is it possible to automate a webpage without moving the mouse pointer?
Yes it is. Simply use the ’PerformClick’ instead of the normal ’Click’ method when working with web adapters like
’DivTag’, ’Input’ or ’Link’.
What are the system requirements for developing and running Ranorex
tests?
The following link to our online documentation shows what is needed to develop or to simply run Ranorex tests.
System Requirements
655
Contents
Are there known incompatibilities with other software?
In general, there are no known incompatibilities. However, some antivirus or security software blocks certain Ranorex
functionality. Consequently, if you experience problems with your automation and are running antivirus or security
software, we recommend temporarily switching that software off for a test run.
656

Online Document Converter

This website help webmasters to achieve a better user experience. Instead of putting a link to download their prices lists and another type of documents, you can simply send a special link to this service, and we will show your document to your users directly without the need of downloading a special application or installing another browsers plugin. Currently, we can read about hundred the most used database files. Moreover, your users can share this document directly on social networks, giving your document additional page views. By using this service, you can save costs by not overloading your own web server, give your users a better way to read documents online without any problems, and allow them to easily download converted copy for offline reading in a format they like.


Previous 10

Next 10