用UIAutomation做驗收測試
這是被測的應用程序: 應用.NET 3.0提供的UIAutomation,我們可以用以下步驟來進行 測試 : 1. 啟動應用程序 C#代碼 string path=@ "ThePathToTheApplication" ; Processprocess=Process.Start(path); string path = @"The Path To The Application";Process
這是被測的應用程序:
應用.NET 3.0提供的UIAutomation,我們可以用以下步驟來進行
測試:
1. 啟動應用程序
- string path = @"The Path To The Application";
- Process process = Process.Start(path);
string path = @"The Path To The Application";Process process = Process.Start(path);
2. 獲得主窗口對應的AutomationElement
- Thread.Sleep(1000);
- AutomationElement aeMainWindow = AutomationElement.FromHandle(process.MainWindowHandle);
Thread.Sleep(1000);AutomationElement aeMainWindow = AutomationElement.FromHandle(process.MainWindowHandle);
3. 獲得按鈕對應的AutomationElement
- AutomationElement aeHelloButton = aeMainWindow.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button));
AutomationElement aeHelloButton = aeMainWindow.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button));
4. 點擊按鈕
此處的GetCurrentPattern相當于Query Interface,Pattern也是UIAutomation的精髓所在。給不同的UI框架做不同的adapter,實現各種各樣的pattern,也就是建立了一個概念上的大一統UI。
- InvokePattern ipHelloButton = (InvokePattern) aeHelloButton.GetCurrentPattern(InvokePattern.Pattern);
- ipHelloButton.Invoke();
InvokePattern ipHelloButton = (InvokePattern) aeHelloButton.GetCurrentPattern(InvokePattern.Pattern);ipHelloButton.Invoke();
5. 獲得文本框對應的AutomationElement
- AutomationElement aeHelloTextBox = aeMainWindow.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
AutomationElement aeHelloTextBox = aeMainWindow.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
6. 取得文本框中的文本
- TextPattern tpHelloTextBox = (TextPattern) aeHelloTextBox.GetCurrentPattern(TextPattern.Pattern);
- string text = tpHelloTextBox.DocumentRange.GetText(-1);
TextPattern tpHelloTextBox = (TextPattern) aeHelloTextBox.GetCurrentPattern(TextPattern.Pattern);string text = tpHelloTextBox.DocumentRange.GetText(-1);
7. 監聽窗口被關閉事件
- Automation.AddAutomationEventHandler(WindowPattern.WindowClosedEvent, aeMainWindow, TreeScope.Element, HandleMainWindowClose);
- private static void HandleMainWindowClose(object sender, AutomationEventArgs e)
- {
- Console.WriteLine("Main Window Closed");
- }
Automation.AddAutomationEventHandler(WindowPattern.WindowClosedEvent, aeMainWindow, TreeScope.Element, HandleMainWindowClose);private static void HandleMainWindowClose(object sender, AutomationEventArgs e){ Console.WriteLine("Main Window Closed");}
8. 關閉窗口
process.Kill();
此時控制臺上就會打印出"Main Window Closed"
整個過程演示了三個主要功能:
1、如何主動去操縱界面(點擊按鈕)
2、如何取得界面的狀態(獲得文本)
3、如何監聽界面的事件(關閉窗口事件)
結論:
UIAutomation可以給Win32,
WindowsForms, WPF編寫的應用程序撰寫
驗收測試。
原文轉自:http://www.kjueaiud.com