应用.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();
process.Kill();
此时控制台上就会打印出"Main Window Closed"
整个过程演示了三个主要功能:
1、如何主动去操纵界面(点击按钮)
2、如何取得界面的状态(获得文本)
3、如何监听界面的事件(关闭窗口事件)
结论:
UIAutomation可以给Win32, WindowsForms, WPF编写的应用程序撰写验收测试。
延伸阅读
文章来源于领测软件测试网 https://www.ltesting.net/