Partager via


Bibliothèque de tests UI Automation

La bibliothèque de tests UI Automation (bibliothèque de tests UIA) est une API appelée par le pilote application dans un scénario de test automatisé. Le pilote est l’application qui obtient un élément Automation (iUIAutomationElement objet) à partir d’un contrôle qui nécessite une vérification et le fournit à la bibliothèque de tests UI Automation. Ensuite, la bibliothèque de tests vérifie et valide l’implémentation UI Automation. Pour en savoir plus sur les éléments UI Automation et Automation, consultez Principes de base d’UI Automation.

Workflow de la bibliothèque de tests UI Automation

Le diagramme suivant montre un flux de travail de test qui incorpore la bibliothèque de tests UI Automation à l’aide d’une application console en tant que pilote. Dans ce cas, le pilote démarre une instance de Notepad.exe et obtient un élément Automation (autrement dit, un IUIAutomationElement objet) à partir du contrôle d’édition. Ensuite, le pilote crée un objet de bibliothèque de tests UI Automation basé sur la plateforme d’interface utilisateur testée, puis passe l’élément Automation en tant que paramètre. La bibliothèque de tests UI Automation détermine que l’élément Automation est un type de contrôle document , puis exécute les tests de contrôle Document, le texte et scroll les tests de modèles de contrôle et les tests d’éléments d’automatisation génériques.

Diagramme montrant le flux de Pilote vers Application vers Driver vers UIATestLibrary à l’aide de flèches rouges.

Journalisation avec la bibliothèque de tests UI Automation

La bibliothèque de tests UI Automation utilise des DLL externes pour journaliser les résultats des exécutions de test. Il prend en charge la journalisation en tant que code XML et la journalisation dans la console.

Journalisation XML

La journalisation XML est généralement utilisée par Visual UI Automation Verify, mais elle peut également être incorporée dans un flux de travail de ligne de commande.

Si la journalisation XML est spécifiée, l’application de pilote doit sérialiser la sortie en créant un objet XmlWriter et en le transmettant à la méthode XmlLog.GetTestRunXml. Le pilote peut ensuite utiliser le code XML sérialisé en interne ou l’écrire dans un fichier.

Les DLL suivantes sont requises pour la journalisation XML.

  • WUIALogging.dll
  • WUIALoggerXml.dll

Journalisation de la console

Par défaut, la bibliothèque de tests UI Automation utilise la journalisation de la console, où toutes les sorties de journalisation sont redirigées en texte brut vers la fenêtre de console. WUIALogging.dll est nécessaire pour la journalisation de la console.

Configuration requise pour la journalisation

Une application de pilote doit inclure les extraits de code suivants pour utiliser la journalisation de la bibliothèque de tests UI Automation.

\\ Include logging functionality.
using Microsoft.Test.UIAutomation.Logging;

...

\\ Select a logger.
UIAVerifyLogger.SetLoggerType(LogTypes.DefaultLogger | 
                              LogTypes.ConsoleLogger | 
                              LogTypes.XmlLogger);

...

\\ Output comment to selected logger.
UIAVerifyLogger.LogComment("...");

Exemples de journalisation

Les exemples suivants illustrent les fonctionnalités de journalisation de base et montrent comment utiliser l’API bibliothèque de tests UI Automation dans une application de pilote d’automatisation de test de base.

//---------------------------------------------------------------------------
//
// Description: Sample logger.
//
//---------------------------------------------------------------------------
using System;

namespace WUITest
{
    using Microsoft.Test.UIAutomation.Logging;

    public sealed class TestMain
    {
        private TestMain() { }

        /// -----------------------------------------------------------------
        /// <summary>
        /// Entry point
        /// </summary>
        /// -----------------------------------------------------------------
        [STAThread]
        static void Main(string[] args)
        {
            // Call SetLogger() if you don't want to use the default logger.
            // To set the logger type, call SetLogger(<string>).
            // <string> can be specified from the command line or from the 
            // the UI Automation Test Library enumeration:
            //  
            //     Logger.SetLogger(LogTypes.ConsoleLogger);
            //     Logger.SetLogger(LogTypes.DefaultLogger);

            Logger.SetLogger(LogTypes.DefaultLogger);

            Logger.StartTest("Test 1");
            Logger.LogComment("This is a comment");
            Logger.LogError(new Exception("My error"), false);
            Logger.EndTest();

            Logger.StartTest("Test 2");
            Logger.LogComment("This is a second comment");
            Logger.LogPass();
            Logger.EndTest();

            Logger.ReportResults();

        }
    }
}
//---------------------------------------------------------------------------
//
// Description: Sample test automation.
//
//---------------------------------------------------------------------------

using System;
using System.Windows;

namespace WUITest
{
    using System.Diagnostics;
    using System.Threading;
    using System.Windows.Automation;
    using Microsoft.Test.UIAutomation;
    using Microsoft.Test.UIAutomation.Core;
    using Microsoft.Test.UIAutomation.TestManager;
    using Microsoft.Test.UIAutomation.Tests.Controls;
    using Microsoft.Test.UIAutomation.Tests.Patterns;
    using Microsoft.Test.UIAutomation.Tests.Scenarios;
    using Microsoft.Test.UIAutomation.Logging;

    public sealed class TestMain
    {

        // Time in milliseconds to wait for the application to start.
        static int MAXTIME = 5000;
        // Time in milliseconds to wait before trying to find the application.
        static int TIMEWAIT = 100; 

        /// -------------------------------------------------------------------
        /// <summary>
        /// Start Notepad, obtain an AutomationElement object, and run tests.
        /// </summary>
        /// -------------------------------------------------------------------
        [STAThread]
        static void Main(string[] args)
        {
            // Dump the information to the console window.  
            // Use a different LogTypes value if you need to dump to another logger, 
            // or create your own logger that complies with the interface.
            UIAVerifyLogger.SetLoggerType(LogTypes.ConsoleLogger);

            // Get the automation element.
            AutomationElement element = StartApplication("NOTEPAD.EXE", null);

            // Call the UI Automation Test Library tests.
            TestRuns.RunAllTests(element, true, TestPriorities.Pri0, 
                    TestCaseType.Generic, false, true, null);

            // Clean up.
            ((WindowPattern)element.GetCurrentPattern(WindowPattern.Pattern)).Close();

            // Dump the summary of results.
            UIAVerifyLogger.ReportResults();
        }

        /// -------------------------------------------------------------------------
        /// <summary>
        /// Start the application and retrieve its AutomationElement. 
        /// </summary>
        /// -------------------------------------------------------------------------
        static public AutomationElement StartApplication(string appPath, 
                string arguments)
        {
            Process process;

            Library.ValidateArgumentNonNull(appPath, "appPath");

            ProcessStartInfo psi = new ProcessStartInfo();

            process = new Process();
            psi.FileName = appPath;

            if (arguments != null)
            {
                psi.Arguments = arguments;
            }

            UIAVerifyLogger.LogComment("Starting({0})", appPath);
            process.StartInfo = psi;

            process.Start();

            int runningTime = 0;
            while (process.MainWindowHandle.Equals(IntPtr.Zero))
            {
                if (runningTime > MAXTIME)
                    throw new Exception("Could not find " + appPath);

                Thread.Sleep(TIMEWAIT);
                runningTime += TIMEWAIT;

                process.Refresh();
            }

            UIAVerifyLogger.LogComment("{0} started", appPath);

            UIAVerifyLogger.LogComment("Obtained an AutomationElement for {0}", appPath);
            return AutomationElement.FromHandle(process.MainWindowHandle);

        }
    }
}