Compartilhar via


Como: Criar uma regra de validação personalizada

Você pode criar suas próprias regras de validação.Para fazer isso, você deriva sua própria classe de regra de uma classe de regra de validação.Regras de validação derivam o ValidationRule classe base.

Visual Studio Team System Test Edition fornece algumas regras de validação predefinidas. Para obter mais informações, consulte Sobre regras de validação.

Observação:

Você também pode criar regras de extração personalizadas.Para obter mais informações, consulte Sobre as regras de extração.

Criar regras de validação personalizadas

  1. Abra um projeto de teste que contém um teste da Web.

  2. (Opcional) Crie um projeto de biblioteca de classes separado na qual deseja armazenar sua regra de validação.

    Observação importante:

    Você pode criar a classe no projeto mesmo que os testes estão em.No entanto, se você quiser reutilizar a regra, é melhor criar um projeto de biblioteca de classes separado para armazenar sua regra.Se você criar um projeto separado, conclua as etapas neste procedimento opcionais.

  3. (Opcional) No projeto de biblioteca de classes, adicione uma referência para a DLL Microsoft.VisualStudio.QualityTools.WebTestFramework.

  4. Criar uma classe que deriva de ValidationRule classe. Implementar o Validate e RuleName membros.

  5. (Opcional) Crie o novo projeto biblioteca de classes.

  6. (Opcional) No projeto de teste, adicione uma referência para o projeto de biblioteca de classes que contém a regra de validação personalizada.

  7. No projeto teste, abra um teste da Web no Editor de teste da Web.

  8. Para adicionar a regra de validação personalizada a uma solicitação de teste da Web, clicar com o botão direito do mouse em uma solicitação e selecionar Adicionar regra de validação.

    The Adicionar regra de validação caixa de diálogo é exibida.Você verá sua regra de validação personalizada no selecionar uma regralista de , juntamente com as regras de validação predefinidas.Selecione sua regra de validação personalizada e clique em OK.

  9. Execute seu teste da Web.

Exemplo

O código a seguir mostra uma implementação de uma regra de validação personalizada.Esta regra de validação imita o comportamento da regra de validação predefinida marca necessária.Use esse exemplo sistema autônomo um ponto de partida para suas próprias regras de validação personalizada.

using System;
using System.Diagnostics;
using System.Globalization;
using Microsoft.VisualStudio.TestTools.WebTesting;

namespace SampleWebTestRules
{
    //-------------------------------------------------------------------------
    // This class creates a custom validation rule named "Custom Validate Tag"
    // The custom validation rule is used to check that an HTML tag with a 
    // particular name is found one or more times in the HTML response.
    // The user of the rule can specify the HTML tag to look for, and the 
    // number of times that it must appear in the response.
    //-------------------------------------------------------------------------
    public class CustomValidateTag : ValidationRule
    {
        /// Specify a name for use in the user interface.
        /// The user sees this name in the Add Validation dialog box.
        //---------------------------------------------------------------------
        public override string RuleName
        {
            get { return "Custom Validate Tag"; }
        }

        /// Specify a description for use in the user interface.
        /// The user sees this description in the Add Validation dialog box.
        //---------------------------------------------------------------------
        public override string RuleDescription
        {
            get { return "Validates that the specified tag exists on the page."; }
        }

        // The name of the required tag
        private string RequiredTagNameValue;
        public string RequiredTagName
        {
            get { return RequiredTagNameValue; }
            set { RequiredTagNameValue = value; }
        }

        // The minimum number of times the tag must appear in the response
        private int MinOccurrencesValue;
        public int MinOccurrences
        {
            get { return MinOccurrencesValue; }
            set { MinOccurrencesValue = value; }
        }

        // Validate is called with the test case Context and the request context.
        // These allow the rule to examine both the request and the response.
        //---------------------------------------------------------------------
        public override void Validate(object sender, ValidationEventArgs e)
        {
            bool validated = false;
            int numTagsFound = 0;

            foreach (HtmlTag tag in e.Response.HtmlDocument.GetFilteredHtmlTags(RequiredTagName))
            {
                Debug.Assert(string.Equals(tag.Name, RequiredTagName, StringComparison.InvariantCultureIgnoreCase));

                if (++numTagsFound >= MinOccurrences)
                {
                    validated = true;
                    break;
                }
            }

            e.IsValid = validated;

            // If the validation fails, set the error text that the user sees
            if (!validated)
            {
                if (numTagsFound > 0)
                {
                    e.Message = String.Format("Only found {0} occurences of the tag", numTagsFound);
                }
                else
                {
                    e.Message = String.Format("Did not find any occurences of tag '{0}'", RequiredTagName);
                }
            }
        }
    }
}
Imports System
Imports System.Diagnostics
Imports System.Globalization
Imports Microsoft.VisualStudio.TestTools.WebTesting

Namespace SampleWebTestRules

    '-------------------------------------------------------------------------
    ' This class creates a custom validation rule named "Custom Validate Tag"
    ' The custom validation rule is used to check that an HTML tag with a 
    ' particular name is found one or more times in the HTML response.
    ' The user of the rule can specify the HTML tag to look for, and the 
    ' number of times that it must appear in the response.
    '-------------------------------------------------------------------------
    Public Class CustomValidateTag
        Inherits Microsoft.VisualStudio.TestTools.WebTesting.ValidationRule

        ' Specify a name for use in the user interface.
        ' The user sees this name in the Add Validation dialog box.
        '---------------------------------------------------------------------
        Public Overrides ReadOnly Property RuleName() As String
            Get
                Return "Custom Validate Tag"
            End Get
        End Property

        ' Specify a description for use in the user interface.
        ' The user sees this description in the Add Validation dialog box.
        '---------------------------------------------------------------------
        Public Overrides ReadOnly Property RuleDescription() As String
            Get
                Return "Validates that the specified tag exists on the page."
            End Get
        End Property

        ' The name of the required tag
        Private RequiredTagNameValue As String
        Public Property RequiredTagName() As String
            Get
                Return RequiredTagNameValue
            End Get
            Set(ByVal value As String)
                RequiredTagNameValue = value
            End Set
        End Property

        ' The minimum number of times the tag must appear in the response
        Private MinOccurrencesValue As Integer
        Public Property MinOccurrences() As Integer
            Get
                Return MinOccurrencesValue
            End Get
            Set(ByVal value As Integer)
                MinOccurrencesValue = value
            End Set
        End Property

        ' Validate is called with the test case Context and the request context.
        ' These allow the rule to examine both the request and the response.
        '---------------------------------------------------------------------
        Public Overrides Sub Validate(ByVal sender As Object, ByVal e As ValidationEventArgs)

            Dim validated As Boolean = False
            Dim numTagsFound As Integer = 0

            For Each tag As HtmlTag In e.Response.HtmlDocument.GetFilteredHtmlTags(RequiredTagName)

                Debug.Assert(String.Equals(tag.Name, RequiredTagName, StringComparison.InvariantCultureIgnoreCase))

                numTagsFound += 1
                If numTagsFound >= MinOccurrences Then

                    validated = True
                    Exit For
                End If
            Next

            e.IsValid = validated

            ' If the validation fails, set the error text that the user sees
            If Not (validated) Then
                If numTagsFound > 0 Then
                    e.Message = String.Format("Only found {0} occurences of the tag", numTagsFound)
                Else
                    e.Message = String.Format("Did not find any occurences of tag '{0}'", RequiredTagName)
                End If
            End If
        End Sub
    End Class
End Namespace

Consulte também

Tarefas

Como: Adicionar uma regra de validação para um teste da Web

Demonstra Passo a passo: Adicionando validação and Extraction Rules to a Web teste

Como: Criar a Custom regra de extração

Referência

ValidationRule

Microsoft.VisualStudio.TestTools.WebTesting.Rules

ValidateFormField

ValidationRuleFindText

ValidationRuleRequestTime

ValidationRuleRequiredAttributeValue

ValidationRuleRequiredTag