Usually my WebTests are coded WebTests, but sometimes the plain WebTest can do the job a lot faster.
My biggest problem working with plain WebTests, is that all the input to my forms are the recorded values. In some of the text fields I need value variations every run.
To solve this problem I created a WebTest plugin. This plugin creates a couple of Context variables on the PreWebTest event. These variables can easily be used in the WebTest using the: {{VAR_NAME}} syntax.
- {{RANDOM}} – Gives you a random string of 5 characters
- {{RANDOMNUM}} – Gives you a string of 4 random numeric characters
- {{TIME_STAMP}} – Gives you a time stamp as a string
Just copy the code below into a C# Class Library project and compile. You can now connect your WebTest to this WebTestPlugin.
using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.TestTools.WebTesting; namespace MyPlugin { public class RandomGenerator : WebTestPlugin { public override void PreWebTest(object sender, PreWebTestEventArgs e) { Random ran = new Random(); e.WebTest.Context["RANDOM"] = GetRandomString(5); e.WebTest.Context["RANDOMNUM"] = GetRandomNumberString(4); e.WebTest.Context["TIME_STAMP"] = GetTimeStamp(); } public override void PostWebTest(object sender, PostWebTestEventArgs e) { } /// <summary> /// Creates a random uppercase string with the letters A-Z /// </summary> /// <param name="length">Length of the string to generate</param> /// <returns>A random generated string of upper case characters</returns> protected string GetRandomString(int length) { Random ran = new Random(); char[] chArray = new char[length]; for (int i = 0; i < length; i++) { chArray[i] = (char)ran.Next(65, 90); } return new string(chArray); } /// <summary> /// Creates a random string with numeric characters /// </summary> /// <param name="length">Length of the string to generate</param> /// <returns>A random generated string of numeric characters</returns> protected string GetRandomNumberString(int length) { Random ran = new Random(); char[] chArray = new char[length]; for (int i = 0; i < length; i++) { chArray[i] = (char)ran.Next(48, 57); } return new string(chArray); } /// <summary> /// Creates a timestamp /// </summary> /// <returns>The timestamp as a string</returns> protected String GetTimeStamp() { DateTime dt = DateTime.Now; return dt.ToShortDateString() + " " + dt.ToLongTimeString() + ":" + dt.Millisecond; } } }
Colorized by: CarlosAg.CodeColorizer