Search This Blog

Welcome to Machers Blog

Blogging the world of Technology and Testing which help people to build their career.

Tuesday, August 12, 2008

VSTS Performance Testing

Visual Studio Team System Understanding Web Tests

What is web test?

A Web test, also called a declarative Web test, consists of a series of HTTP requests. Web tests work at the protocol layer by issuing HTTP requests. Web tests do not run JavaScript. JavaScript actions can be simulated at runtime by using Web test plug-ins, Web test request plug-ins, extraction rules, or coded Web tests.
Web tests are used to test the functionality of Web applications and to test Web applications under load. Web tests are used both in performance tests and stress tests.
Web tests can be created by recording activities in a browser session. Also build Web tests manually by using the Web Test Editor.
To test Web applications, you create Web tests by recording a test that navigates through a Web application.
Benefits:
Create Web tests for use in an extensive set of testing purposes:
• Create functional tests that exercise your Web applications.
• Create data-driven tests.
• Create and run tests that can test the performance of your applications.
• Use .NET languages for test authoring, debugging, and test extensibility.
Web tests automatically handle these aspects of HTTP:
• Hidden field correlation including VIEWSTATE
• Redirects
• Dependent requests
• Authentication
• Security through HTTPS/SSL
Coded Web Tests
Web test starts as a list of URLs, representing Web requests, in the Web Test Editor. If necessary, these requests can be converted to Visual C# or Visual Basic code, called a coded Web test. After a Web test has been converted to its coded format, looping and branching constructs can be added.
To convert a recorded Web test
1. Open a solution that contains a recorded Web test.
2. Open the Web test file.
3. Click the Generate Code button on the toolbar in the Web Test Editor.
You are prompted for a name for the coded Web test.
4. Type an appropriate name in the dialog box for the coded Web test class that is generated, and then click OK.
5. Click Build, and then click Build Solution from the menu.
Your code compiles.
To run a coded Web test
1. On the Test menu, click Windows and then click Test View.
2. Right-click your coded Web test and select Run Selection.
3. Click OK to run your test. The test runs immediately.
In the Test Results window, the test result is displayed as In Progress until your test completes running. At this point, Passed or Failed is displayed. It displays Failed if the test throws an exception or if a validation/extraction rule fails.

Using Validation and Extraction Rules
Validation rules help verify that a Web application is working correctly by validating the existence of text, tags, or attributes on the page returned by a Web request. Validation rules can also verify the time it takes a request to finish, and the existence of form fields and their values.
Extractions rules help verify that a Web application is working correctly by extracting data from the responses to Web requests. Extraction rules store results in the test context as name value pairs. Extraction rules can extract form fields, text, attributes, headers, regular expressions, and hidden fields.
How to: Add a Validation Rule to a Web Test
Validation rules help verify that a Web application is working correctly by validating the existence of text, tags, or attributes on the page returned by a Web request. Validation rules can also verify the amount of time it takes a request to finish, and the existence of form fields and their values.

To add a validation rule to a Web test
1. Open a Web test.
For more information about how to create a Web test, see Creating a Web Test.
2. In the Web Test Editor, select the request to which you want to add a validation rule.
3. Right-click the request and select Add Validation Rule.
The Add Validation Rule dialog box is displayed.
4. In the Add Validation Rule dialog box, select a rule to configure, for example select Find Text. Find Text is a validation rule that looks for a specific string in the HTTP response to your request. For information about other predefined validation rules, see About Validation Rules.
5. For the Find Text property, type a string that you expect to appear in the response body when the test runs.
6. Set the Pass If Text Found property to True.
7. Click OK to close the Add Validation Rule dialog box.
8. On the File menu click Save to save the Web test.
9. In the Web Test Editor, click Run to start your Web test.
The Web Test Viewer is displayed.
10. In the top pane of the Web Test Viewer, click the request to which you added the validation rule.
11. In the bottom pane of the Web Test Viewer, click the Details tab.
The Validation and Extraction Rules grid is displayed with an entry for the validation rule you just added. Verify that the validation rule worked as expected

How to: Create a Custom Validation Rule:

You can create your own validation rules. To do this, you derive your own rule class from a validation rule class. Validation rules derive from the Validation Rule base class. Visual Studio Team System Test Edition provides some predefined validation rules.
To create custom validation rules
1. Open a Test Project that contains a Web test.
2. (Optional) Create a separate Class library project in which to store your validation rule.
Important Note:

You can create the class in the same project that your tests are in. However, if you want to reuse the rule, it is better to create a separate Class library project in which to store your rule. If you create a separate project, you must complete the optional steps in this procedure.
3. (Optional) In the Class library project, add a reference to the Microsoft.VisualStudio.QualityTools.WebTestFramework DLL.
4. Create a class that derives from the Validation Rule class. Implement the Validate and Rule Name members.
5. (Optional) Build the new Class library project.
6. (Optional) In the Test Project, add a reference to the Class library project that contains the custom validation rule.
7. In the Test Project, open a Web test in the Web Test Editor.
8. To add the custom validation rule to a Web test request, right-click a request and select Add Validation Rule.
The Add Validation Rule dialog box appears. You will see your custom validation rule in the Select a rule list, together with the predefined validation rules. Select your custom validation rule and then click OK.
9. Run your Web test.
Example
The following code shows an implementation of a custom validation rule. This validation rule mimics the behavior of the predefined Required Tag validation rule. Use this example as a starting point for your own custom validation rules.

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);
}
}
}
}
}

How to: Add an Extraction Rule to a Web Test

Extraction rules help verify that a Web application is working correctly by extracting data from the responses to Web requests. Extraction rules store results in the test context as name value pairs. Extraction rules can extract form fields, text, attributes, headers, regular expressions, and hidden fields.

To add an extraction rule to a Web test
1. Open a Web test.
For more information about how to create a Web test, see Creating a Web Test.
2. In the Web Test Editor, select the request to which you want to add the extraction rule.
3. Right-click the request and select Add Extraction Rule.
The Add Extraction Rule dialog box is displayed.
4. In the Add Extraction Rule dialog box, in the Select a rule pane, select a rule to configure. For example, select Extract Attribute Value. For information about other predefined extraction rules, see About Extraction Rules.
5. In the Properties for selected rule pane, set the Context Parameter Name property to a descriptive name such as FirstLink. When the extraction rule runs, a context variable named FirstLink is created that contains the extracted string.
6. Set the Attribute Name property to href and the TagName property to a.
Note:
The HTML format of what we are trying to extract in this example is a href=http://www.contoso.com, where a is referred to as the tag and href is the attribute of interest.
7. Click OK to close the Add Extraction Rule dialog box.
8. On the File menu click Save to save the Web test.
9. In the Web Test Editor, click Run to start your Web test.
The Web Test Viewer is displayed.
10. In the top pane of the Web Test Viewer, click the request to which you added the validation rule.
11. In the bottom pane of the Web Test Viewer, click the Details tab.
The Validation and Extraction Rules grid is displayed with an entry for the extraction rule you just added.
12. Click the Context tab.
A grid of names and values is displayed. The last entry will be the FirstLink variable and its value. The value should match the first a href on the requested page. You can verify this by viewing the requested page in a browser, viewing the source of the page, and searching for the first href.




How to: Create a Custom Extraction Rule

You can create your own extraction rules. To do this, you derive your own rules from an extraction rule class. Extraction rules derive from the Extraction Rule base class. Visual Studio Team System Test Edition provides some predefined extraction rules
To create a custom extraction rule
1. Open a Test Project that contains a Web test.
2. (Optional) Create a separate Class library project in which to store your extraction rule.
Important Note:
You can create the class in the same project that your tests are in. However, if you want to reuse the rule, it is better to create a separate C lass library project in which to store your rule. If you create a separate project, you must complete the optional steps in this procedure.
3. (Optional) In the Class library project, add a reference to the Microsoft.VisualStudio.QualityTools.WebTestFramework dll.
4. Create a class that derives from the ExtractionRule class. Implement the Extract and RuleName members.
5. (Optional) Build the new Class library project.
6. (Optional) In the Test Project, add a reference to the Class library project that contains the custom extraction rule.
7. In the Test Project, open a Web test in the Web Test Editor.
8. To add the custom extraction rule, right-click a Web test request and select Add Extraction Rule.
The Add Extraction Rule dialog box appears. You will see your custom validation rule in the Select a rule list, together with the predefined validation rules. Select your custom extraction rule and then click OK.
9. Run your Web test.
Example
The following code shows an implementation of a custom extraction rule. This extraction rule extracts the value from a specified input field. Use this example as a starting point for your own custom extraction rules.
C#
Copy Code
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.WebTesting;
using System.Globalization;

namespace ClassLibrary2
{
//-------------------------------------------------------------------------
// This class creates a custom extraction rule named "Custom Extract Input"
// The user of the rule specifies the name of an input field, and the
// rule attempts to extract the value of that input field.
//-------------------------------------------------------------------------
public class CustomExtractInput : ExtractionRule
{
/// Specify a name for use in the user interface.
/// The user sees this name in the Add Extraction dialog box.
//---------------------------------------------------------------------
public override string RuleName
{
get { return "Custom Extract Input"; }
}

/// Specify a description for use in the user interface.
/// The user sees this description in the Add Extraction dialog box.
//---------------------------------------------------------------------
public override string RuleDescription
{
get { return "Extracts the value from a specified input field"; }
}

// The name of the desired input field
private string NameValue;
public string Name
{
get { return NameValue; }
set { NameValue = value; }
}

// The Extract method. The parameter e contains the Web test context.
//---------------------------------------------------------------------
public override void Extract(object sender, ExtractionEventArgs e)
{
if (e.Response.HtmlDocument != null)
{
foreach (HtmlTag tag in e.Response.HtmlDocument.GetFilteredHtmlTags(new string[] { "input" }))
{
if (String.Equals(tag.GetAttributeValueAsString("name"), Name, StringComparison.InvariantCultureIgnoreCase))
{
string formFieldValue = tag.GetAttributeValueAsString("value");
if (formFieldValue == null)
{
formFieldValue = String.Empty;
}

// add the extracted value to the Web test context
e.WebTest.Context.Add(this.ContextParameterName, formFieldValue);
e.Success = true;
return;
}
}
}
// If the extraction fails, set the error text that the user sees
e.Success = false;
e.Message = String.Format(CultureInfo.CurrentCulture, "Not Found: {0}", Name);
}
}
}


How to: Create a Test-level Validation Rule

validation rules to Web tests can be added at the test level. A test-level rule fires on every request in the test. In other words, adding a test-level validation rule is a shortcut for adding the same rule to every request. By default, such rules apply only to top-level requests. In the code of a coded Web test, you can apply test-level validation rules to dependent requests.
One purpose for using a test-level rule is to detect incorrect flow in a test. Errors in the server application could cause such incorrect flow by causing the playback of the Web test to vary from the recorded sequence. You can also create test-level rules to check content length and response time, to validate content that must appear on every page, or to validate that all pages conform to a specific criterion such as accessibility.
There is no way to override or turn off a test-level validation rule for a given request. If a request contains the same validation rule as a test-level rule, both rules will fire.
To add a test-level validation rule
1. Open a Test Project that contains a Web test.
2. Open a Web test in the Web Test Editor.
If at least one test-level validation rule exists, the Validation Rules folder appears after the final request in the test. You can add, delete, and modify validation rules at this level in the same way that you can work with validation rules for an individual request.
3. Right-click the Validation Rules folder and select Add Validation Rule.
- or -
Right-click the Web test node and then select Add Validation Rule.
The Add Validation Rule dialog box appears. Under Select a rule, you see the available predefined and custom validation rules. Select a validation rule.
4. (Optional) Under Properties for selected rule, edit or add options and parameters.
5. Click OK.
6. Run your Web test.

Data Binding in Web Tests
You can use data binding in a Web test to provide the input to HTTP requests in the Web test. For example, you could provide a list of logon names and logon passwords that would be used during the execution of the Web test to try repeated logons.
You can examine your Web tests and decide which part of a test you want to be data-driven. Then you can create a data source for that part of the test. You can bind data in several locations in a Web test.

To add the data source to the Web test
1. In the Web Test Editor, right-click the top node of the Web test and then click Add Data Source.
The New Test Data Source Wizard appears.
2. In the Data source name box type a name for your data source.
3. In the Data source type list click Database.
4. Click Next.
5. Select an existing connection, or follow these steps:
a. Click New Connection.
The Choose Data Source dialog box appears.
b. In the Data source list, click the appropriate source for your database.
c. (Optional) In the Data provider list, click the appropriate provider for your database.
d. (Optional) Clear the Always use this selection check box.
e. Click Continue.
The Connection Properties dialog box appears.
f. Enter the information to connect to your database.
g. (Optional) Click the Test Connection button to verify your connection to the database.
h. Click OK to close the Connection Properties dialog box.
The connection string to access the database is entered in the wizard.
6. Click Next.
7. Under Choose from the available tables for this data source, select the check box next to each table that you want to include in the data source.
8. Click Finish.
If your database is a file, for example a Microsoft Access database, a dialog box appears that asks you if you want to add the file to your current project. You can use the following information to help you decide:
Response Result Advantage
Yes The file is copied to the project. When the project is deployed, there is no extra work that is required.
No The file is not copied to the project. When the project is deployed, you might have to update the path of the file. Some data files can be very large, and should be maintained separate from the project. Some data files must be shared among several members of a team, and should be maintained in a central location that all members can access.
9. Click Yes or No.
A Data Sources node is added to the Web test, and the database and tables appear in the hierarchy.
10. On the File menu click Save to save the Web test.

How to: Add a CSV File Data Source to a Web Test
Before you can add data binding to a Web request, you must add a data source to the Web test. After you add a data source to a Web test, you can bind a Web request to the data. After you add data binding to a Web request, you must configure the test run to access one or more rows of data.
Note:
You can use a CSV file as a data source only if the first row of the CSV file is a row of column headers. If the file does not have a row of column headers,.
To add the data source to the Web test
1. In the Web Test Editor, right-click the top node of the Web test and then click Add Data Source.
The New Test Data Source Wizard appears.
2. In the Data source name box type a name for your data source.
3. In the Data source type list click CSV File.
4. Click Next.
5. In the Choose a CSV file box enter the path and name of the file, or click the ellipsis to browse to the file. For example, enter the following:
\FileName.csv
The data from the CSV file appears in the Preview data pane. The first 1,000 rows of data are displayed.
6. Click Finish.
A dialog box appears that asks you if you want to add the file to your current project. You can use the following information to help you decide:
Response Result Advantage
Yes The file is copied to the project. When the project is deployed, there is no extra work that is required.
No The file is not copied to the project. When the project is deployed, you might have to update the path of the file. Some data files can be very large, and should be maintained separate from the project. Some data files must be shared among several members of a team, and should be maintained in a central location that all members can access.
7. Click Yes or No.
A Data Sources node will be added to the Web test, and the text file will appear as a table in the hierarchy.
8. On the File menu click Save to save the Web test.
How to: Add an XML File Data Source to a Web Test
Before you can add data binding to a Web request, you must add a data source to the Web test. After you add a data source to a Web test, you can bind a Web request to the data. After you add data binding to a Web request, you must configure the test run to access one or more rows of data.
To add the data source to the Web test
1. In the Web Test Editor, right-click the top node of the Web test and then click Add Data Source.
The New Test Data Source Wizard appears.
2. In the Data source name box, type a name for your data source.
3. In the Data source type list, click XML File.
4. Click Next.
5. In the Choose an XML file box, type the path and name of the file, or click the ellipsis to browse to the file. For example, enter the following:
\FileName.xml
6. In the Table drop-down box, select a table.
The data from the XML file appears in the Preview data pane. The first 1,000 rows of data are displayed.
7. Click Next.
8. Under Choose from the available tables for this data source, select the check box next to the table you want.
9. Click Finish.
A dialog box appears that asks you if you want to add the file to your current project. You can use the following information to help you decide:
Response Result Advantage
Yes The file is copied to the project. When the project is deployed, there is no extra work that is required.
No The file is not copied to the project. When the project is deployed, you might have to update the path of the file. Some data files can be very large, and should be maintained separate from the project. Some data files must be shared among several members of a team, and should be maintained in a central location that all members can access.
10. Click Yes or No.
A Data Sources node will be added to the Web test, and the text file will appear as a table in the hierarchy.
11. On the File menu, click Save to save the Web test.

How to: Add Data Binding to a Web Request:
Before you can add data binding to a Web request, you must add a data source to your Web test.
After you add data binding to a Web request, you must configure the test run to access one or more rows of data
To add data binding to a Web test
1. In the Web Test Editor, find a request that you want to bind. You might have to expand the Form Post Parameters folder, and locate a specific form field.
2. Click the node that you want to bind.
3. In the Properties window, find the Value property.
4. Click the property, and then click the down arrow that appears.
5. Expand the data source that you want to use, expand the table that you want to use, and then click the column that you want to use.
The request is now bound to the data source.
Note:
If the data source you want to bind to is not available, click Add Data Source at the bottom of the property pane to add a new data source. If a data source changes after you bind to it, you can click Refresh Columns at the bottom of the property pane to update the columns available.
6. On the File menu, click Save to save the Web test.
How to: Add Data Binding to a Web Service Request
To add data binding to a Web service test
1. Open a Web test that contains a Web service request.
The Web Test Editor is displayed.
2. Find a Web service request in the request tree that you want to bind to a data source. Select the String Body node under it.
3. In the Properties window, click the ellipsis (…) in the String Body property.
The Edit HTTP Body String window appears.
4. Replace values in the SOAP body with data bound values by using the following syntax:
{{DataSourceName.TableName.ColumnName}}
For example, if you have the following code:




string
string
int



You can change it to the following:




{{DataSourceName.Users.Name}}
{{DataSourceName.Users.Password}}
{{DataSourceName.Orders.OrderID}}



5. Click OK to close the Edit HTTP Body String window.
6. On the File menu, click Save to save the Web test.

How to: Configure Data Binding in a Web Test
• Before you can add data binding to a Web request, you must add a data source to your Web test.
• After you add a data source to a Web request, you can bind a Web test request to the data.
After you have bound a Web test to a data source, you must configure how many times you want the Web test to access the data. For example, if your data source contains 5,000 rows, you can first run the test using just 10 rows as a test. Then you can run the test using all the rows in the data source.
To configure data binding in a Web test
1. On the Test menu, point to Edit Test Run Configurations, and then click Local Test Run.
The localtestrun.testrunconfig dialog box appears.
Note:
Instead of editing the Local Test Run configuration, you can also create a separate data run configuration for testing your data binding. Then you can switch between run configurations.
2. Select Web Test in the left pane.
3. Click the One run per data source row option.
- or -
Click the Fixed run count option, and enter the number of rows of data to test.
Note:
No matter which option that you select, the test will start on the first row of data and move sequentially through the data.
4. Click Apply and then click Close.
5. On the File menu, menu click Save to save the Web test.
Advanced Web Test Tasks
Recorded Web tests provide a foundation to develop highly customized Web testing functions. The information in following topics expands upon the built-in functionality of recorded Web tests so that you can perform customized testing.
How to: Use the Web Test API
You can write code for your Web tests. The Web test API is used to create coded Web tests, Web test plug-ins, request plug-ins, requests, extraction rules, and validation rules. The classes that make up these types are the core classes in this API. The other types in this API are used to support creating WebTest, WebTestPlugin, WebTestRequestPlugin, WebTestRequest, ExtractionRule, and ValidationRule objects. You use the Microsoft.VisualStudio.TestTools.WebTesting namespace to create customized Web tests.
You can also use the Web test API to programmatically create and save declarative Web tests. To do this, use the T:Microsoft.VisualStudio.TestTools.WebTesting.DeclarativeWebTest and T:Microsoft.VisualStudio.TestTools.WebTesting.DeclarativeWebTestSerializer classes.
Tip:

Use the object browser to examine the Microsoft.VisualStudio.TestTools.WebTesting namespace. Both the C# and Visual Basic editors offer IntelliSense support for coding with the classes in the namespace.
You can also create plug-ins for load tests. For more information, see How to: Create a Load Test Plug-In.
Using the Web test API
1. Open a test project that contains a Web test.
For more information, see How to: Create a Test Project.
2. Add a C# or a Visual Basic class library project to your test solution.
3. Add a reference in the test project to the class library project.
4. Add a reference to the Microsoft.VisualStudio.QualityTools.WebTestFramework dll in the class library project.
5. In the class file located in the class library project, add a using statement for the Microsoft.VisualStudio.TestTools.WebTesting namespace.
6. Implement any of the core classes in the namespace in the class library project. For an example implementation of WebTestPlugin, see How to: Create a Web Test Plug-In. You can write the rest of the code that you need, and then build the project.
7. Run your Web test.
Using Plug-ins
A plug-in is custom code that you write and attach to a Web test or an HTTP request within a Web test. When you create a plug-in class, you inherit from the corresponding base class in the Web test framework. These classes are WebTestPlugin and WebTestRequestPlugin.
How to: Create a Web Test Plug-In
Web tests plug-ins enable you to isolate and reuse code outside the main declarative statements in your Web test. A customized Web test plug-in offers you a way to call some code as the Web test is run. The Web test plug-in is run one time for every test iteration. In addition, if you override the PreRequest or PostRequest methods in the test plug-in, those request plug-ins will run before or after each request, respectively.
You can create a customized Web test plug-in by deriving your own class from the WebTestPlugin base class.
You can use customized Web test plug-ins with the Web tests you have recorded, which enables you to write a minimal amount of code to attain a greater level of control over your Web tests. However, you can also use them with coded Web tests. For more information, see How to: Create a Coded Web Test.
Note:
You can also create load test plug-ins. For more information, see How to: Create a Load Test Plug-In.

To create a custom Web test plug-in
1. Open a test project that contains a Web test.
For more information about how to create a test project, see How to: Create a Test Project.
2. Create a class library project in which to store your Web test and a Web test plug-in.
3. Select the class library project and then right-click Add Reference.
4. On the .NET tab, select Microsoft.VisualStudio.QualityTools.WebTestFramework. Click OK.
5. In your test project, right-click and select Add Reference.
6. On the Projects tab, select the new class library. Click OK.
7. Write the code of your plug-in. First, create a new public class that derives from WebTestPlugin.
8. Implement code inside one or both of the PreWebTest and M:Microsoft.VisualStudio.TestTools.WebTesting.WebTestPlugin.PostWebTest(System.Object,Microsoft.VisualStudio.TestTools.WebTesting.PostWebTestEventArgs) event handlers.
9. After you have written the code, build the new project.
10. Open a Web test.
11. To add the Web test plug-in, click Set Web Test Plug-in on the toolbar. This displays your test plug-in in the Set Web Test Plug-in dialog box. Select your class and then click OK.
Note:
You can also change the Web test plug-in in the Properties window. Select the Web test node and press F4. In the Properties window, you see the Plug-in category and the plug-ins you have added to the Web test.
Example
The following code creates a customized Web test plug-in that adds an item to the WebTestContext that represents the test iteration.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TestTools.WebTesting;

namespace SampleRules
{
public class SampleWebTestPlugin : WebTestPlugin
{
// start counting iterations at 1 not 0
// so that the iteration number we give matches the run number
static int testIterationNumber = 1;

public override void PostWebTest(object sender, PostWebTestEventArgs e)
{
}

public override void PreWebTest(object sender, PreWebTestEventArgs e)
{
e.WebTest.Context["TestIterationNumber"] = testIterationNumber;
testIterationNumber++;
}
}
}
How to: Create a Request-Level Plug-In
Requests are the declarative statements that constitute Web tests. Web tests plug-ins enable you to isolate and reuse code outside the main declarative statements in your Web test. You can create plug-ins and add them to an individual request as well as to the Web test that contains it. A customized request plug-in offers you a way to call code as a particular request is run in a Web test.
Note:
In Visual Studio 2005 Team Edition for Testers, it was possible to create a request plug-in at the test level that ran for every request in the test. In Team System 2008 Test Edition, test-level plug-ins support the request-plug-in interface and will apply to every request in the test. When Team System 2008 Test Edition encounters a request plug-in that was created in Visual Studio 2005, it converts the plug-in to an equivalent test-level plug-in.
Every Web test request plug-in has a PreRequest method and a PostRequest method. After you attach a request plug-in to a particular http request, the PreRequest event will be fired before the request is issued and the PostRequest fired after the response is recieved.
You can create a customized Web test request plug-in by deriving your own class from the WebTestRequestPlugin base class.
You can use customized Web test request plug-ins with the Web tests you have recorded. Customized Web test request plug-ins enable you to write a minimal amount of code to attain a greater level of control over your Web tests. However, you can also use them with coded Web tests. For more information, see How to: Create a Coded Web Test.
To create a request-level plug-in
1. Open a test project that contains a Web test.
For more information about how to create a test project, see How to: Create a Test Project.
2. In the same solution, create a class library project in which to store your request plug-in.
3. Select the class library project and then right-click Add Reference.
4. On the .NET tab, select Microsoft.VisualStudio.QualityTools.WebTestFramework. Click OK.
5. In your test project, right-click and select Add Reference.
6. On the Projects tab, select the new class library project. Click OK.
7. Write the code of your plug-in. First, create a new public class that derives from WebTestRequestPlugin.
8. Implement code inside one or both of the PreRequest and PostRequest event handlers.
9. After you have written the code, build the new project.
10. Open the Web test to which you want to add the request plug-in.
11. Right-click the request to which you want to add the plug-in, and then select Add Request Plug-in.
The Add Web Test Request Plug-in dialog box is displayed.
12. Under Select a plug-in, select your new plug-in and then click OK.
The plug-in is added to the Request Plug-ins folder, which is a child folder of the http request.
Example
You can use the following code to create a customized Web test plug-in.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Microsoft.VisualStudio.TestTools.WebTesting;

namespace RequestPluginNamespace
{
public class MyWebRequestPlugin : WebTestRequestPlugin
{
public override void PostRequest(object sender, PostRequestEventArgs e)
{
MessageBox.Show(e.WebTest.Context.AgentName);
}
public override void PreRequest(object sender, PreRequestEventArgs e)
{
MessageBox.Show(e.Request.Url);
}
}
}
How to: Create a Web Service Test
Updated: November 2007
You can use a Web test to test Web services. By using the Insert Request and Insert Web Service Request options, you can customize the individual requests in the Web Test Editor to locate Web service pages. Typically, you do not display these pages in the Web application. Therefore, you must customize the request to gain access to these pages.
The following procedures use a Web service that is contained within the Commerce Starter Kit. You can download it from ASP.NET Starter Kits.
Note:

You can test a Web service that is not hosted on a Web server by using the ASP.NET Development Server.
To test a Web service
1. Create a new Web test. As soon as the browser opens, click Stop.
2. In the Web Test Editor, right-click the Web test and select Add Web Service Request.
3. In the Url property of the new request, type the name of the Web service, such as http://localhost/storecsvs/InstantOrder.asmx.
4. Open a separate session of the browser and type the URL of the .asmx page in the Address toolbar. Select the method that you want to test and examine the SOAP message. It contains a SOAPAction.
5. In the Web Test Editor, right-click the request and select Add Header to add a new header. In the Name property, type SOAPAction. In the Value property, type the value that you see in SOAPAction, such as "http://tempuri.org/CheckStatus".
6. In the String Body node, put text/xml in the Content Type property.
7. Return to the browser in step 4, select the XML portion of the SOAP request from the Web service description page and copy it to the clipboard.
8. The XML content resembles the following example:




string
string
int



9. Return to the Web Test Editor and then click the ellipsis (…) in the String Body property. Paste the contents of the clipboard into the property.
10. You must replace any placeholder values in the XML with valid values for the test to pass. In the previous sample you would replace the two instances of string and one int. This Web service operation will only complete if there is a registered user who has placed an order.
11. Right-click the Web service request and select Add URL QueryString Parameter.
12. Assign the query string parameter a name and value. In the previous example, the name is op and the value is CheckStatus. This identifies the Web service operation to perform.
Note:

You can use data binding in the SOAP body to replacing any placeholder value with data bound values by using the {{DataSourceName.TableName.ColumnName}} syntax. For more information, see How to: Add Data Binding to a Web Request.

13. Run the test. In the top pane of the Web Test Viewer, select the Web service request. In the bottom pane, select the Web Browser tab. The XML that is returned by the Web service, and the results of any operations, will be displayed.

No comments: