如何:创建自定义验证规则

更新:2007 年 11 月

您可以创建自己的验证规则。若要实现此目的,可以从某个验证规则类派生自己的规则类。验证规则从 ValidationRule 基类派生。

Visual Studio Team System Test Edition 提供了一些预定义的验证规则。有关更多信息,请参见关于验证规则

说明:

也可以创建自定义提取规则。有关更多信息,请参见关于提取规则

创建自定义验证规则

  1. 打开包含 Web 测试的测试项目。

  2. (可选)创建一个将在其中存储验证规则的单独的类库项目。

    重要说明:

    您可以在测试所在的项目中创建类。但是,如果您希望重用规则,则最好创建一个单独的类库项目来存储规则。如果创建单独的项目,则必须完成本过程中的可选步骤。

  3. (可选)在该类库项目中,添加一个对 Microsoft.VisualStudio.QualityTools.WebTestFramework DLL 的引用。

  4. 创建一个从 ValidationRule 类派生的类。实现 ValidateRuleName 成员。

  5. (可选)生成新的类库项目。

  6. (可选)在测试项目中添加一个对包含自定义验证规则的类库项目的引用。

  7. 在测试项目中,在“Web 测试编辑器”中打开一个 Web 测试。

  8. 将自定义验证规则添加到 Web 测试请求,请右击请求并选择“添加验证规则”。

    将出现“添加验证规则”对话框。您将在“选择规则”列表中看到您的自定义验证规则以及预定义的验证规则。选择您的自定义验证规则,然后单击“确定”。

  9. 运行 Web 测试。

示例

下面的代码演示如何实现自定义验证规则。此验证规则模仿预定义的“所需的标记”验证规则的行为。可基于该示例创建您自己的自定义验证规则。

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

请参见

任务

如何:向 Web 测试添加验证规则

演练:向 Web 测试添加验证和提取规则

如何:创建自定义提取规则

参考

ValidationRule

Microsoft.VisualStudio.TestTools.WebTesting.Rules

ValidateFormField

ValidationRuleFindText

ValidationRuleRequestTime

ValidationRuleRequiredAttributeValue

ValidationRuleRequiredTag