Codificando uma regra de validação personalizada para um teste de desempenho para Web
Publicado: abril de 2016
Você pode criar suas próprias regras de validação. Para fazer isso, você deve derivar sua própria classe de regra de uma classe de regra de validação. As regras de validação derivam-se da classe base ValidationRule.
O Visual Studio Enterprise fornece algumas regras de validação predefinidas. Para obter mais informações, consulte [obsoleto] Usando regras de validação e extração em testes de desempenho na Web.
Dica
Também é possível criar regras de extração personalizadas.Para obter mais informações, consulte Criar código personalizado e plug-ins para testes de carga.
Requisitos
- O Visual Studio Enterprise
Para criar regras de validação personalizadas
Abra um projeto de teste que contenha um teste de desempenho na Web.
(Opcional) Crie um projeto de biblioteca de classes separado na qual armazenar a regra de validação.
Importante
Você pode criar a classe no mesmo projeto em que estão seus testes.No entanto, se desejar reutilizar a regra, é melhor criar um projeto de biblioteca de classes separado no qual armazenar a regra.Se você criar um projeto separado, será preciso concluir as etapas opcionais neste procedimento.
(Opcional) No projeto de biblioteca de classes, adicione uma referência à DLL Microsoft.VisualStudio.QualityTools.WebTestFramework.
Crie uma classe que derive da classe ValidationRule. Implemente os membros Validate e RuleName.
(Opcional) Crie o novo projeto de biblioteca de classes.
(Opcional) No projeto de teste, adicione uma referência ao projeto de biblioteca de classes que contenha a regra de validação personalizada.
No projeto de teste, abra um teste de desempenho na Web no Editor de Teste de Desempenho na Web.
Para adicionar a regra de validação personalizada a uma solicitação de teste de desempenho na Web, clique em uma solicitação e selecione Adicionar regra de validação.
A caixa de diálogo Adicionar regra de validação é exibida. Você verá sua regra de validação personalizada na lista Selecione uma regra, juntamente com as regras de validação predefinidas. Selecione sua regra de validação personalizada e escolha OK.
Execute o teste de desempenho na Web.
Exemplo
O código a seguir mostra uma implementação de uma regra de validação personalizada. Essa regra de validação imita o comportamento da regra de validação de marca obrigatória predefinida. Use este exemplo como ponto de partida para suas próprias regras de validação personalizadas.
Aviso
As propriedades públicas no código de um validador personalizado não podem conter valores nulos.
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
ValidationRule
Microsoft.VisualStudio.TestTools.WebTesting.Rules
ValidateFormField
ValidationRuleFindText
ValidationRuleRequestTime
ValidationRuleRequiredAttributeValue
ValidationRuleRequiredTag
[obsoleto] Usando regras de validação e extração em testes de desempenho na Web
[obsoleto] Como adicionar uma regra de validação a um teste de desempenho na Web
[obsoleto] Adicionando regras validação e extração a um teste de desempenho na Web
Codificando uma regra de extração personalizada para um teste de desempenho para Web