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.
[TestModule("D451F1D1-C347-4B58-939F-F6187642EB56", ModuleType.UserCode, 1)]
public class UsingRepository : ITestModule
{
// Repository object to access UI elements
MyFirstTestProjectRepository repo = MyFirstTestProjectRepository.Instance;
/// <summary>
/// Constructs a new instance.
/// </summary>
public UsingRepository()
{
// Do not delete - a parameterless constructor is required!
}
void ITestModule.Run()
{
Mouse.DefaultMoveTime = 300;
Keyboard.DefaultKeyPressTime = 100;
Delay.SpeedFactor = 1.0;
// Using Ranorex.Form adapter represented by 'MyApp'
// 'MyApp' is used as a folder within the repository;
// the 'Self' property returns an object of type Ranorex.Form
// Activates application
repo.MyApp.Self.Activate();
// Log 'Active' state
Report.Info(repo.MyApp.Self.Active.ToString());
// Maximize, Minimize and Restore
repo.MyApp.Self.Maximize();
repo.MyApp.Self.Minimize();
repo.MyApp.Self.Restore();
// Closes application
repo.MyApp.Self.Close();
// Using Ranorex.Button adapter represented by 'ButtonAdd'
// Read and log value of 'Text' attribute
Report.Info(repo.MyApp.Buttons.ButtonAdd.Text);
// Press button
repo.MyApp.Buttons.ButtonAdd.Press();
// Read and log value of 'Enabled' attribute
Report.Info(repo.MyApp.Buttons.ButtonAdd.Enabled.ToString());
// Using Ranorex.RadioButton adapter
// represented by 'GenderOption'
// Select radio button
repo.MyApp.GenderOption.Select();
// Accessing listitems of Ranorex.List adapter
// represented by 'CategoryList'
IList<ranorex.listitem> listItems = repo.MyApp.CategoryList.Items;
foreach ( Ranorex.ListItem item in listItems )
{
Report.Info(item.Text + " is member of CategoryList");
}
// Using Ranorex.MenuItem to open 'File' menu
repo.MyApp.MenuItemFile.Select();
// Selecting sub menu item 'Connect'
repo.FileMenu.Connect.Select();
// Read and log 'Enabled' state of menu item 'Connect'
Report.Info(repo.FileMenu.Connect.Enabled.ToString());
}
}
Public Class UsingRepository Implements ITestModule ' Repository object to access UI elements Private repo As MyFirstTestProjectRepository = MyFirstTestProjectRepository.Instance ''' <summary> ''' Constructs a new instance. ''' </summary> ' Do not delete - a parameterless constructor is required! Public Sub New() End Sub ''' <summary> ''' Performs the playback of actions in this module. ''' </summary> ''' <remarks>You should not call this method directly, instead pass the module ''' instance to the <see cref="TestModuleRunner.Run(ITestModule)"> method ''' that will in turn invoke this method.</see></remarks> Private Sub ITestModule_Run() Implements ITestModule.Run Mouse.DefaultMoveTime = 300 Keyboard.DefaultKeyPressTime = 100 Delay.SpeedFactor = 1.0 ' Using Ranorex.Form adapter represented by 'MyApp' ' 'MyApp' is used as a folder within the repository; ' the 'Self' property returns a Ranorex.Form object ' Activates application repo.MyApp.Self.Activate() ' Log 'Active' state Report.Info(repo.MyApp.Self.Active.ToString()) ' Maximize, Minimize and Restore repo.MyApp.Self.Maximize() repo.MyApp.Self.Minimize() repo.MyApp.Self.Restore() ' Closes application repo.MyApp.Self.Close() ' 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
// 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);
' 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)
// Creating adapter of type 'NativeWindow' using the "...Info" object
Ranorex.NativeWindow nativeWnd = repo.MyApp.SelfInfo.CreateAdapter<Ranorex.NativeWindow>(false);
// ... and read value of attribute 'ProcessName'
Report.Info("Process name of VIP Database: " + nativeWnd.ProcessName);
// Using Control Adapter to access properties and methods of
// .NET WinForms control
Ranorex.Control winFormsControl = repo.MyApp.SelfInfo.CreateAdapter<Ranorex.Control>(false);
// Set background color of VIP application to Color.Black using the
// exposed property 'BackColor'
winFormsControl.SetPropertyValue("BackColor",Color.Black);
// Report screenshot after changing the background color
Report.Screenshot(repo.MyApp.Self);
// Closes VIP Database by invoking the 'Close' method
// exposed by the System.Windows.Forms.Form class
winFormsControl.InvokeMethod("Close");
' Creating adapter of type 'NativeWindow' using the "...Info" object
Dim nativeWnd As Ranorex.NativeWindow = repo.MyApp.SelfInfo.CreateAdapter(Of Ranorex.NativeWindow)(False)
' ... and read value of attribute 'ProcessName'
Report.Info("Process name of VIP Database: " & nativeWnd.ProcessName)
' Using Control Adapter to access properties and methods of
' .NET WinForms control
Dim winFormsControl As Ranorex.Control = repo.MyApp.SelfInfo.CreateAdapter(Of Ranorex.Control)(False)
' Set background color of VIP application to Color.Black using the
' exposed property 'BackColor'
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 using the "Info" object
IList<Ranorex.Button> buttonList =
repo.MyApp.EnabledButtonsInfo.CreateAdapters<Ranorex.Button>();
// Move the mouse pointer to each button of the list
// and add a screenshot for each to the report
foreach (Ranorex.Button button in buttonList )
{
button.MoveTo();
Report.Screenshot(button);
}
' 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
// 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);
' 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.
Ranorex.Cell cellObject = null;
// Try to find a cell object using two
// different RanoreXPath expressions
bool found=false;
found = Host.Local.TryFindSingle<Ranorex.Cell>("/form//table/row/cell[3]", 2000, out cellObject);
found = Host.Local.TryFindSingle<Ranorex.Cell>("/form//table/row/cell[4]", 2000, out cellObject);
// If none of the expressions returns an object
// throw new 'ElementNotFoundException' and test case fails
if (!found)
{
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");
}
}
Dim cellObject As Ranorex.Cell = Nothing
' Try to find a cell object using two
' different RanoreXPath expressions
Dim found As Boolean = Host.Local.TryFindSingle(Of Ranorex.Cell)("/form//table/row/cell[3]", 2000, cellObject)
found = Host.Local.TryFindSingle(Of Ranorex.Cell)("/form//table/row/cell[4]", 2000, cellObject)
' If none of the expressions returns an object
' throw new 'ElementNotFoundException' and test case fails
If Not found Then
Throw New Ranorex.ElementNotFoundException("Both RanoreXPath with no return", Nothing)
Else
' If the value of 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
void ITestModule.Run()
{
Mouse.DefaultMoveTime = 300;
Keyboard.DefaultKeyPressTime = 100;
Delay.SpeedFactor = 1.0;
}
Private Sub ITestModule_Run() Implements ITestModule.Run
Mouse.DefaultMoveTime = 300
Keyboard.DefaultKeyPressTime = 100
Delay.SpeedFactor = 1.0
End Sub
// ----------------- 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.CurrentRow.ToString());
' ----------------- 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.CurrentRow.ToString())
// Create Ranorex.Button adapter using 'FindSingle' method
// from Host.Local (starting at root node) with absolute RanoreXPath
// Note: ElementNotFound exception is thrown if item is not found within
// the specified timeout of 2000 ms.
Ranorex.Button addButtonVar1 = Host.Local.FindSingle<Ranorex.Button>("/form[@controlname='formVipApplication']/button[@controlname='btAdd']",2000);
addButtonVar1.MoveTo();
// Alternatively you can use the 'TryFindSingle' method to prevent
// a test case from failing because of an exception thrown if
// the element is not found within the specified timeout of 2000 ms
Ranorex.Button addButtonVar2 = null;
bool found = Host.Local.TryFindSingle<Ranorex.Button>("/form[@controlname='formVipApplication']/button[@controlname='btAdd']", 2000, out addButtonVar2);
// Move mouse pointer to button
addButtonVar2.MoveTo();
// Request a list of buttons shown from the VIP Database application
// and create a screenshot for each button in the report file
IList<Ranorex.Button> buttonList = Host.Local.Find<Ranorex.Button>("/form[@controlname='formVipApplication']/button",500);
foreach (Ranorex.Button bt in buttonList)
{
Report.Screenshot(bt);
}
// Using find methods in combination with existing Ranorex repository items
Ranorex.Button btAdd = repo.MyApp.Self.FindSingle<Ranorex.Button>("button[@controlname='btAdd']",2000);
' 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)
// 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");
' Create bitmap to search for
' within application form and
' click it
Dim bmp As Bitmap = Ranorex.Imaging.Load("..\..\Green Sea Turtle Small.bmp")
' Performs a right click on the image found
' within the application window based
' on the image location
myRepo.WinFormsApp.Self.Click(MouseButtons.Right, bmp)
' You can also search for images that are slightly different to the
' loaded image by specifying the minimum Similarity for a match (95% = 0.95).
myRepo.WinFormsApp.Self.Click(new Location(bmp, new Imaging.FindOptions(0.95)))
' OR Set the default Similarity value for all following image operations
Imaging.FindOptions.Default.Similarity = 0.95
myRepo.WinFormsApp.Self.Click(bmp)
Report.Success("Image displayed successfully")
// 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");
}
' 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.
A common problem in UI testing is the appearance of an unexpected dialog - e.g. the Update-Check dialog in KeePass.
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.
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<ranorex.button>().Click();
}
public static void CloseUpdateCheckDialog(Ranorex.Core.RxPath myPath, Ranorex.Core.Element myElement)
{
myElement.As<ranorex.button>().Click();
}
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
Download Test Automation Guide
(PDF file, 20MB)