论坛首页 编程语言技术论坛

用UIAutomation做验收测试

浏览 5512 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2007-05-16  
这是被测的应用程序:




应用.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编写的应用程序撰写验收测试。
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics