[img]http://taowen.iteye.com/upload/picture/pic/3365/b3b4e70f-3a2d-45fb-9598-2200c704077d.png[/img]
[img]http://taowen.iteye.com/upload/picture/pic/3366/c6038ae3-566b-4f0f-a7a4-4e96c192012b.png[/img]
應用.NET 3.0提供的UIAutomation,我們可以用以下步驟來進行測試:
1. 啓動應用程序
string path = @"The Path To The Application";
Process process = Process.Start(path);
2. 獲得主窗口對應的AutomationElement
Thread.Sleep(1000);
AutomationElement aeMainWindow = AutomationElement.FromHandle(process.MainWindowHandle);
3. 獲得按鈕對應的AutomationElement
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();
5. 獲得文本框對應的AutomationElement
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);
7. 監聽窗口被關閉事件
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編寫的應用程序撰寫驗收測試。