Compartilhar via


Usando automação de interface do usuário para testes automatizados

Observação

Esta documentação destina.Os desenvolvedores do NET Framework que desejam usar o gerenciado UI Automation classes definidas na System.Windows.Automation namespace.As informações mais recentes sobre UI Automation, consulte API de automação do Windows: Automação da interface do usuário.

This overview describes how Microsoft UI Automation can be useful as a framework for programmatic access in automated testing scenarios.

UI Automation provides a unified object model that enables all user interface (UI) frameworks to expose complex and rich functionality in an accessible and easily automated manner.

UI Automationfoi desenvolvido como um sucessor Microsoft Active Accessibility. Active Accessibilityuma estrutura existente foi projetada para fornecer uma solução para tornar os controles e aplicativos acessíveis. Active Accessibilitynão foi projetado com a automação de teste em mente, mesmo que ele evoluiu para essa função devido a requisitos de acessibilidade e automação muito semelhantes. UI Automation, in addition to providing more refined solutions for accessibility, is also specifically designed to provide robust functionality for automated testing. For example, Active Accessibility relies on a single interface to both expose information about the UI and collect the information needed by AT products; UI Automation separates the two models.

Both a provider and client are required to implement UI Automation for it to be useful as an automated test tool. UI Automation providers are applications such as Microsoft Word, Excel, and other third-party applications or controls based on the Microsoft Windows operating system. UI Automation clients include automated test scripts and assistive technology applications.

Observação

The intent of this overview is to showcase the new and improved automated testing capabilities of UI Automation.This overview is not intended to provide information on accessibility features and will not address accessibility other than where necessary.

Este tópico contém as seguintes seções.

  • UI Automation in a Provider
  • UI Automation in a Client
  • Related Tools and Technologies
  • Security
  • Tópicos relacionados

UI Automation in a Provider

For a UI to be automated, a developer of an application or control must look at what actions an end-user can perform on the UI object using standard keyboard and mouse interaction.

Uma vez principais ações foram identificadas, o correspondente UI Automation padrões de controle (ou seja, o padrões de controle que espelham a funcionalidade e o comportamento da UI elemento) devem ser implementadas no controle. For example, user interaction with a combo box control (such as the run dialog) typically involves expanding and collapsing the combo box to hide or display a list of items, selecting an item from that list, or adding a new value via keyboard input.

Observação

With other accessibility models, developers must gather information directly from individual buttons, menus, or other controls.Unfortunately, every control type comes in dozens of minor variations.In other words, even though ten variations of a pushbutton may all work the same way and perform the same function, they must all be treated as unique controls.There is no way to know that these controls are functionally equivalent.Control patterns were developed to represent these common control behaviors.For more information, see Visão Geral de Padrões de Controle de Automação de Interface de Usuário.

Implementing UI Automation

As mentioned earlier, without the unified model provided by UI Automation, test tools and developers are required to know framework-specific information in order to expose properties and behaviors of controls in that framework. Since there can be several different UI frameworks present at any single time within Windows operating systems, including Win32, Windows Forms, and Windows Presentation Foundation (WPF), it can be a daunting task to test multiple applications with controls that seem similar. For example, the following table outlines the framework-specific property names required to retrieve the name (or text) associated with a button control and shows the single equivalent UI Automation property.

UI Automation Control Type

UI Framework

Framework Specific Property

UI Automation Property

Button

Windows Presentation Foundation

Content

NameProperty

Button

Win32

Caption

NameProperty

Image

HTML

alt

NameProperty

UI Automation providers are responsible for mapping the framework-specific properties of their controls to the equivalent UI Automation properties.

Information on implementing UI Automation in a provider can be found at Provedores de Automação de IU para Código Gerenciado. Information on implementing control patterns is available at Padrões de controle de automação de interface do usuário and Padrão de Automação de Texto de Interface de Usuário.

UI Automation in a Client

The goal of many automated test tools and scenarios is the consistent and repeatable manipulation of the user interface. This can involve unit testing specific controls through to the recording and playback of test scripts that iterate through a series of generic actions on a group of controls.

A complication that arises from automated applications is the difficulty synchronizing a test with a dynamic target. For example, a list box control, such as one contained in the Windows Task Manager, that displays a list of currently running applications. Since the items in the list box are dynamically updated outside the control of the test application, attempting to repeat the selection of a specific item in the list box with any consistency is impossible. Similar issues can also arise when attempting to repeat simple focus changes in a UI that is outside the control of the test application.

Programmatic Access

Acesso programático fornece a capacidade para imitar, por meio de código, qualquer interação e experiência exposto pelo tradicional do mouse e teclado. UI Automationpermite o acesso através de programação por meio de cinco componentes:

Key Properties for Test Automation

The ability to uniquely identify and subsequently locate any control within the UI provides the basis for automated test applications to operate on that UI. There are several Microsoft UI Automation properties used by clients and providers that assist in this.

AutomationID

Identifica exclusivamente um o elemento de automação de seus irmãos. AutomationIdPropertynão foi localizado, ao contrário de uma propriedade, como NameProperty que está localizado normalmente se um produto é vendido em vários idiomas. See Use the AutomationID Property.

Observação

AutomationIdProperty does not guarantee a unique identity throughout the automation tree.For example, an application may contain a menu control with multiple top-level menu items that, in turn, have multiple child menu items.These secondary menu items may be identified by a generic scheme such as "Item1, Item 2, Item3, etc.", allowing duplicate identifiers for children across top-level menu items.

ControlType

Identifies the type of control represented by an automation element. Significant information can be inferred from knowledge of the control type. See Visão Geral dos Tipos de Controle de Automação de Interface do Usuário.

NameProperty

Esta é uma seqüência de texto que identifica ou explica um controle. NamePropertydeve ser usado com cautela, pois podem ser localizado. See UI Automation Properties Overview.

Implementing UI Automation in a Test Application

Add the UI Automation References.

O UI Automation a necessidade da dll para clientes de automação da interface do usuário são listados aqui.

Add the System.Windows.Automation namespace.

This namespace contains everything UI Automation clients need to use the capabilities of UI Automation except text handling.

Add the System.Windows.Automation.Text namespace.

This namespace contains everything a UI Automation clients need to use the capabilities of UI Automation text handling.

Find controls of interest

Automated test scripts locate UI Automation elements that represent controls of interest within the automation tree.

There are multiple ways to obtain UI Automation elements with code.

Observação

An AutomationIdProperty can be obtained using a tool such as UISpy.exe (interface do usuário Spy) that is able to itemize the UI Automation properties of a control.

  • Use o TreeWalker classe percorrer todo o UI Automation árvore ou um subconjunto deles.

  • Track focus.

  • Use the hWnd of the control.

  • Use screen location, such as the location of the mouse cursor.

See Obtendo elementos da automação interface do usuário

Obtain Control Patterns

Control patterns expose common behaviors for functionally similar controls.

After locating the controls that require testing, automated test scripts obtain the control patterns of interest from those UI Automation elements. For example, the InvokePattern control pattern for typical button functionality or the WindowPattern control pattern for window functionality.

See Visão Geral de Padrões de Controle de Automação de Interface de Usuário.

Automate the UI

Scripts de teste automatizado agora podem controlar qualquer UI de interesse de um UI framework usando as informações e a funcionalidade exposta pelo UI Automation padrões de controle.

There are a number of related tools and technologies that support automated testing with UI Automation.

  • UISpy.exe (interface do usuário Spy)é um graphical user interface (GUI) aplicativo que pode ser usado para reunir UI Automation informações para ambos provedor e cliente de desenvolvimento e depuração. UI Spyestá incluído na Windows Software Development Kit (SDK).

  • UIAutoCmd is a command-line tool with capabilities similar to UI Spy.

  • MSAABridge exposes UI Automation information to Active Accessibility clients. The primary goal of bridging UI Automation to Active Accessibility is to allow existing Active Accessibility clients the ability to interact with any framework that has implemented UI Automation.

Security

For security information, see Visão geral de segurança da automação de interface do usuário.

Consulte também

Outros recursos

Fundamentos de Automação de Interface de Usuário