コード サンプル
この章では、Ranorex API を使用してコード モジュールを記述し、ユーザー固有のコードでレコーディング モジュールを拡張するためのコード サンプルについて説明します。
コード内でのリポジトリの使用
[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 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>
''' 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
' 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
リポジトリを使用した UI 要素の待機
各アイテムとフォルダー タイプは、’Info’ を宣言された追加のオブジェクトを提供します。このオブジェクトは、アイテムに関連する属性にアクセスするために使用されます。このオブジェクトを使用することで、Ranorex が UI 要素に直接アクセスして例外をスローしてしまうのを防ぐことができます。Info オブジェクトの主な用途は、アイテムまたはフォルダー パスが正しいかどうかを確認することです。アイテムに対して設定されたタイムアウト値とこのオブジェクトを併用することで、ダイアログ、テキスト値、Web コンテンツなどの UI 要素を待機できます。
// 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)
多数のプロパティやメソッドにアクセスするためのアダプターの作成
Ranorex Spy で VIP データベース アプリケーション フォームを解析すると、このアプリケーション ウィンドウには 3 つのアダプター (Form, Control, NativeWindow) があることが分かります。Ranorex.Form アダプターとすべての属性/メソッドには、リポジトリのアプリケーション フォルダー ‘MyApp’ を使用して直接アクセスできます。’ProcessName’ のようなプロパティにアクセスする場合や、.NET WinForms コントロールによって公開されるメソッドを呼び出す場合は、Form アダプターを NativeWindow または Control に変換する必要があります。以下のコードを見るとわかるように、目的のアダプターを作成するために ‘…Info’ オブジェクトが使用されます。
メモ
WinForms コントロールによって公開されているプロパティまたはメソッドにアクセスするには、それらの名前を知っている必要があります。このコントロールの API について十分な知識がない場合は、アプリケーションの開発者に確認してください。
// Creating adapter of type 'NativeWindow' using the "...Info" object
Ranorex.NativeWindow nativeWnd = repo.MyApp.SelfInfo.CreateAdapter(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(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")
リポジトリ要素からのアダプター リストの作成
ひとつのリポジトリ アイテムの RanoreXPath に複数の要素がマッチする場合は、CreateAdapters メソッドを使用して、アダプターのリストを作成します。
複数の要素を提供するリポジトリ アイテムの作成方法については、⇢ リポジトリ アイテムの追加 を参照してください。
// 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);
}
' 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 クラスの使用
Ranorex.Validate クラスは、UI 要素の値を確認するために使用されますが、UI に関連しないオブジェクトを単純に比較するためにも使用できます。シンプルな IF ステートメントとは対照的に、Validate クラスのメソッドでは、失敗または成功メッセージがレポートに自動的に記録されます。
メモ
Validate クラスで提供される各メソッドは、バリデーションが失敗した場合に例外がスローされないようにすることができます。上記のコード スニペットで使用されているバリデーション メソッドはごく一部です。Ranorex.Validate クラスの詳細については、API ドキュメントを参照してください。
// 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)
Validate クラスを使用した、テスト ケースの強制的な失敗
前述のように、Validate クラスを使用すると、UI に関連するオブジェクトと UI に関連しないオブジェクトの値を比較して、テストを失敗または成功にすることができます。これ以外にも、比較をおこなわずにテスト ケースを強制的に失敗させることもできます。
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");
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
例外を使用した、テスト ケースの強制的な失敗
Ranorex は、テスト ケースの実行が失敗したか成功したかを決定するために、例外処理を使用します。いずれの Ranorex メソッド (Ranorex.Validate メソッドや、無効なリポジトリ アイテムの使用など) によっても例外がスローされなければ、テストの実行は成功します。Ranorex が例外をスローしないようにすると同時に、テスト ケースが失敗するかどうかをユーザーが独自に決定したい場合は、Ranorex 例外をスローするコードを記述する必要があります。
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 || 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");
}
}
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)
' 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
テスト実行速度の設定
必要に応じて、テストの実行速度を指定および変更できます。レコーディングによって生成されたコードでは、コード モジュール内で使用されているものと同じプロパティを使用して、リプレイ速度が定義されます。新規に作成されるコード モジュールでは、実行速度を指定する 3 行のコードが、’Run’ メソッドに最初から含まれます。
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
テスト ケースおよびテスト スイート コンテキストへのアクセス
コード モジュールまたはレコーディング内で UI から読み取った値を、テスト ケース内の次のモジュールに送る必要がある場合があります。以下のコード例で使用されているモジュール変数 varDialogTextA (コード モジュール A) と varDialogTextB (コード モジュール B) はいずれも、テスト ケース内でデータを受け渡すために、テスト ケースのデータ バインディング ダイアログで指定されたパラメーターにバインドされています。
// ----------------- 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());
' ----------------- 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())
高度なコード例
アイテムを検索するために、API で提供される様々な ‘Find’ メソッドを使用して、RanoreXPath 式をコード内で直接使用することもできます。’Host.Local’ を使用して、要素の検索をルート レベルから直接開始するか、またはリポジトリ アイテムのような既存のアダプターを再利用して、その場所から検索を開始します。
// 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);
' 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)
イメージ ベース オートメーションの実行
Ranorex が GUI 要素の一部をはっきりと識別できない場合、’Click’ メソッドの暗黙的なイメージ検索メカニズムの使用が有効な場合があります。
// 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")
イメージの検索および比較
イメージを比較するには、’Contains’ メソッドを使用して、既存の Ranorex 要素内に含まれるそのイメージを検索します。
ヒント
いずれの例でも、1 対 1 の比較を実行するために、圧縮されていないファイル (BMP または PNG 形式) がロードされます。類似度、プリプロセス、その他の検索設定をおこなう場合には、FindOptions クラスを使用します。
// 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
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();
}
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
WebDriver の作成と使用
// Create endpoint management factory
var fac = new RemoteEndpointFactory();
// Use existing endpoints
var existing = fac.GetAll();
Report.Log(ReportLevel.Info, string.Format("Endpoints: {0}", existing.Count()));
foreach (var e in existing)
{
Report.Log(ReportLevel.Info, string.Format("Name: {0}", e.DisplayName));
}
// Get WebDriver endpoints form the existing ones (no equivalent for mobile currently)
var webDriverEndpoints = fac.GetAllWebDriverEndpoints();
Report.Log(ReportLevel.Info, string.Format("There are '{0}' WebDriver endpoints", webDriverEndpoints.Count()));
// Create user process endpoint
var ep = fac.CreateTransientWebDriverEndpoint(new WebDriverEndpointInfo("tempEp", "http://localhost:4444/wd/hub"));
var cfg = WebDriverConfiguration.FromJson("{}");
cfg.Name = "MyConfig1";
cfg.Description = "Code sample Config";
ep.ActivateConfiguration(cfg);
ep.ConnectAsync()
.ContinueWith(_ => ep.MakeCurrentHostAsync())
.Wait();
var b = ep.StartBrowser("firefox", "https://support.ranorex.com");
高度なバリデーション – クリップボード
このサンプルでは、クリップボードの現在の内容を、所定の参照値と照合してバリデーションする方法を示します。
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");
}
}
Public Sub Validate_ClipboardContentEqual(compareText As String, customLogMessage As String)
' check if content of clipboard is text
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
高度なバリデーション – テーブル全体
このサンプルでは、テーブル全体の内容 (UI コントロール) を一度にバリデーションする方法を示します。パラメーターとしてテーブルを渡す必要があります。さらに、Ranorex スナップショットのファイル名を指定する必要があります。このスナップショットは参照としての役割を果たし、期待されるテーブルの内容を定義します。
メモ
参照先のスナップショットは、事前に作成する必要があります。Ranorex Spy のツリー ビューでテーブルを選択して、右クリック メニューからスナップショットを保存します。スナップショットの作成については、⇢ Ranorex スナップショットの作成 を参照してください。
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")
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
高度なバリデーション – Web のテーブル全体
このサンプルでは、Web テーブル全体の内容 (HTML タグのテーブル) を一度にバリデーションする方法を示します。パラメーターとしてテーブルを渡す必要があります。さらに、Ranorex スナップショットのファイル名を指定する必要があります。このスナップショットは参照としての役割を果たし、期待される Web テーブルの内容を定義します。
メモ
参照先のスナップショットは、事前に作成する必要があります。Ranorex Spy のツリー ビューでテーブルを選択して、右クリック メニューからスナップショットを保存します。スナップショットの作成については、⇢ Ranorex スナップショットの作成 を参照してください。
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
' 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
高度なバリデーション – ファイル (テキストベース)
このサンプルでは、テキストベース ファイルの内容をバリデーションする方法を示します。ファイルの内容は、参照ファイルの内容と比較されます。したがって、バリデーションするファイルのファイル名の他に、参照ファイルのファイル名も指定する必要があります。
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);
}
}
Public Sub Validate_FileTextEqual(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.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
高度なバリデーション – ファイル (非テキストベース/バイナリー)
このサンプルでは、非テキストベース ファイル (バイナリー ファイル) をバリデーションする方法を示します。ファイルの内容は、参照ファイルの内容と比較されます。したがって、バリデーションするファイルのファイル名の他に、参照ファイルのファイル名も指定する必要があります。
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
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
高度なバリデーション – データベース (単一フィールド)
このサンプルでは、データベース フィールドを所定のテキスト値と照合してバリデーションする方法を示します。データベースにアクセスするには、正しい接続文字列の他に、正しい SQL ステートメントも指定する必要があります。OLE データベース接続については、MSDN を参照してください。
メモ
パフォーマンス上の理由から、単一フィールドにアクセスするメソッドは連続して使用しないでください。テーブル全体、および、SQL の結果全体にアクセスする方法については、この後説明します。
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)
{
// 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();
}
}
}
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()
End Try
End Using
End Sub
高度なバリデーション – データベース (テーブル全体)
このサンプルでは、データベースの内容をバリデーションする方法を示します。この方法によって、テーブル全体、データベース ビュー、または SQL ステートメントのあらゆる結果と照合することができます。正しい SQL ステートメントおよび正しい接続文字列を指定して、データベースへのアクセスを可能にする必要があります。OLE データベース接続については、MSDN を参照してください。
加えて、CSV ファイルのファイル名をパラメーターとして渡す必要もあります。このファイルは参照としての役割を果たし、期待値を含んでいる必要があります。このファイル内の値が、セミコロン (“;”) 以外の方法で区切られている場合、パラメーター “csvSeparator” を使用し、区切り文字を指定してください。
メモ
参照ファイル (CSV ファイル) は、事前に作成する必要があります。この参照ファイルの作成には、任意のテキスト エディターを使用できます。
Public Sub Validate_DatabaseTableWithQuery(OLEConnectionString As String, SQLQuery As String, referenceCSVTable As String, csvSeparator As String, customLogMessageOverall As String, customLogMessageDetail As String)
' 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"
End If
' Log success
Ranorex.Report.Log(Ranorex.ReportLevel.Success, customLogMessageOverall)
Finally
command.Dispose()
SQLReader.Dispose()
CSVReader.Dispose()
End Try
End Using
End Sub
高度なバリデーション – XML コード
このサンプルでは、Ranorex で XML コードをバリデーションする方法を示します。以下に示すメソッドは、最初のパラメーターとして XML コード スニペットを、’node’ パラメーターとして XPath 式を受け取ります。この XPath 式によって、バリデーションするノードが選択されます。’expectedValue’ パラメーターに期待値も指定してください。
ユース ケースと例: このメソッドは、XML 形式の Web サービスの結果をバリデーションする場合に役立ちます。ここでは、一意な ISBN を送信すると書籍の詳細情報を収集する Web サービスを提供するオンライン ライブラリを仮定します。この Web サービスの結果は XML 形式であり、作者、タイトル、発行年など、検出された書籍に関する情報を含んでいます。この XML の結果 (後の XML サンプル コードを参照) は、次の呼び出しを含むコード メソッドを使用してバリデーションできます。
// call method to validate xml code
Validate_XMLResponse(xml, "books/book/@title", "Ranorex Test Automation Guide", "Validating result of web service request ({0} vs. {1})");
メモ
このメソッドは、レコーダーのアクション テーブルから呼び出すこともできます。そのため、ユーザー コード ファイルで、このメソッドが提供される (直接提供されるか、基本クラスからの派生) 必要があります。
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");
}
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);
}
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)
End Sub
サンプルの XML コード
上記のサンプルを実装する XML サンプル コードを以下に示します。
<books>
<book title="Ranorex Test Automation Guide" author="Ranorex" year="2014">
</book>