码迷,mamicode.com
首页 > Web开发 > 详细

转:创建编码的WebTest

时间:2014-07-22 23:13:55      阅读:561      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   java   使用   os   

创建编码的WebTest
?通常,通过将现有的已记录Web测试转换为编码的Web测试来创建编码的Web测试。记录的Web测试以“Web测试编辑器”中可见的请求树开头。编码的Web测试是一个生成一系列WebTestRequest.NET类,可以使用C#Visual Basic编写。可以创建编码的Web测试,但推荐做法是将记录的Web测试转换为编码的Web测试。

?将记录的Web测试转换为编码的Web测试之后,可以像编辑任何其他源代码一样编辑该代码。此外,还可以添加循环和分支结构,动态更改测试中的请求数,以及动态生成测试命中的URL集。
mamicode.com,码迷

生成的代码如下:
namespace PersonalWebsiteTest
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.VisualStudio.TestTools.WebTesting;
    using Microsoft.VisualStudio.TestTools.WebTesting.Rules;

    [DataSource("DataSource1", "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"E:\\My Documents\\Visual Studio 2005\\" +
        "Test.mdb\";Persist Security Info=False", Microsoft.VisualStudio.TestTools.WebTesting.DataBindingAccessMethod.Sequential, "Customer")]
    public class WebTest1Coded : WebTest
    {
        public WebTest1Coded()
        {
            this.PreAuthenticate = true;
        }
        public override IEnumerator<WebTestRequest> GetRequestEnumerator()
        {
            this.BeginTransaction("Login");
            //Web请求1   
            WebTestRequest request1 = new WebTestRequest("http://localhost:40022/Personal%20Website/");
            ExtractHiddenFields rule1 = new ExtractHiddenFields();
            rule1.ContextParameterName = "1";
            request1.ExtractValues += new EventHandler<ExtractionEventArgs>(rule1.Extract);
            yield return request1;
                        
            WebTestRequest request2 = new WebTestRequest("http://localhost:40022/Personal%20Website/default.aspx");
            request2.ThinkTime = 14;
            request2.Method = "POST";
            FormPostHttpBody request2Body = new FormPostHttpBody();
            request2Body.FormPostParameters.Add("__EVENTTARGET", "");
            request2Body.FormPostParameters.Add("__EVENTARGUMENT", "");
            request2Body.FormPostParameters.Add("__VIEWSTATE", this.Context["$HIDDEN1.__VIEWSTATE"].ToString());
            request2Body.FormPostParameters.Add("ctl00$Main$LoginArea$Login1$UserName", "oscarxie");
            request2Body.FormPostParameters.Add("ctl00$Main$LoginArea$Login1$Password", "hae867@!");
            request2Body.FormPostParameters.Add("__EVENTVALIDATION", this.Context["$HIDDEN1.__EVENTVALIDATION"].ToString());
            request2Body.FormPostParameters.Add("ctl00$Main$LoginArea$Login1$LoginButton.x", "110");
            request2Body.FormPostParameters.Add("ctl00$Main$LoginArea$Login1$LoginButton.y", "8");
            request2.Body = request2Body;
            if ((this.Context.ValidationLevel >= Microsoft.VisualStudio.TestTools.WebTesting.ValidationLevel.High))
            {
                ValidationRuleFindText rule2 = new ValidationRuleFindText();
                rule2.FindText = "oscarxie";
                rule2.IgnoreCase = false;
                rule2.UseRegularExpression = false;
                rule2.PassIfTextFound = true;
                request2.ValidateResponse += new EventHandler<ValidationEventArgs>(rule2.Validate);
            }
            yield return request2;

            WebTestRequest request3 = new WebTestRequest("http://localhost:40022/Personal%20Website/Resume.aspx");
            request3.ThinkTime = 3;
            yield return request3;

            WebTestRequest request4 = new WebTestRequest("http://localhost:40022/Personal%20Website/Links.aspx");
            request4.ThinkTime = 2;
            yield return request4;

            WebTestRequest request5 = new WebTestRequest("http://localhost:40022/Personal%20Website/Albums.aspx");
            request5.ThinkTime = 3;
            yield return request5;

            WebTestRequest request6 = new WebTestRequest("http://localhost:40022/Personal%20Website/Default.aspx");
            request6.ThinkTime = 1;
            ExtractHiddenFields rule3 = new ExtractHiddenFields();
            rule3.ContextParameterName = "1";
            request6.ExtractValues += new EventHandler<ExtractionEventArgs>(rule3.Extract);
            yield return request6;

            WebTestRequest request7 = new WebTestRequest("http://localhost:40022/Personal%20Website/Default.aspx");
            request7.Method = "POST";
            FormPostHttpBody request7Body = new FormPostHttpBody();
            request7Body.FormPostParameters.Add("__EVENTTARGET", "ctl00$LoginStatus1$ctl00");
            request7Body.FormPostParameters.Add("__EVENTARGUMENT", "");
            request7Body.FormPostParameters.Add("__VIEWSTATE", this.Context["$HIDDEN1.__VIEWSTATE"].ToString());
            request7Body.FormPostParameters.Add("__EVENTVALIDATION", this.Context["$HIDDEN1.__EVENTVALIDATION"].ToString());
            request7.Body = request7Body;
            yield return request7;

            this.EndTransaction("Login");
        }
    }
}

生成代码的时机:
?只有在正常的Web测试达到极限后,才能生成进行编码的Web测试。在正常的Web测试中,最明显的限制是循环(您无法多次运行请求的子集)和分支(您无法有条件地执行一组请求)。生成代码的其他原因包括细粒度的事件处理以及以编程方式设置参数值。
?使用图形化的Web测试编辑器编辑Web测试比直接编辑代码更容易且较少出错。因此,在生成代码之前,您应该尽可能地获得Web测试。
可以参考文章:Web 测试的创作与调试技术


分支
Web 测试使用数据绑定的用户凭据登录到 Web 站点,如果用户在该系统中不存在,必须创建一个新用户帐户。
 // If the login failed, create a new user account

    if (LastResponse.StatusCode != System.Net.HttpStatusCode.OK)
    {
      WebTestRequest request4 = new WebTestRequest("http://testserver/website/register.aspx");
      request4.ThinkTime = 9;
      ExtractHiddenFields rule2 = new ExtractHiddenFields();
      rule2.ContextParameterName = "1";
      request4.ExtractValues += new EventHandler(rule2.Extract);
      yield return request4;

      WebTestRequest request5 = new WebTestRequest("http://testserver/website/register.aspx");
      request5.ThinkTime = 5;
      request5.Method = "POST";
      FormPostHttpBody request5Body = new FormPostHttpBody();
      request5Body.FormPostParameters.Add("__VIEWSTATE",
this.Context["$HIDDEN1.__VIEWSTATE"].ToString());
      request3Body.FormPostParameters.Add("username",
this.Context["DataSource1.Credentials.UserName"].ToString());
      request3Body.FormPostParameters.Add("password",
this.Context["DataSource1.Credentials.Password"].ToString());
      request5Body.FormPostParameters.Add("confirmpassword",
this.Context["DataSource1.Credentials.Password"].ToString());
      request5.Body = request5Body;
      yield return request5;
    }

循环
 Web 测试执行搜索,然后在搜索结果中连接每个链接。
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TestTools.WebTesting;

public class LoopingCoded : WebTest
{
  public LoopingCoded()
  {
  }

  public override IEnumerator GetRequestEnumerator()
  {
    // Issue a search for the term "Microsoft"

    WebTestRequest request7 = new WebTestRequest("http://testserver/website/Search.aspx");
    request7.ThinkTime = 20;
    request7.Method = "POST";
    FormPostHttpBody request7Body = new FormPostHttpBody();
    request7Body.FormPostParameters.Add("txtSearch", "Microsoft");
    request7.Body = request7Body;
    yield return request7;

    // Loop through each anchor tag in the search result and issue a request to each tag‘s target url (href)

    foreach (HtmlTag tag in this.LastResponse.HtmlDocument.GetFilteredHtmlTags("a"))
    {
      WebTestRequest loopRequest = new WebTestRequest(tag.GetAttributeValueAsString("href"));
      yield return loopRequest;
    }
  }
}

细粒度的事件处理
 Web 测试将两个请求的响应体记录到磁盘,以用于调试和基准调整。
// Log this response out to a file
 WebTestRequest request2 = new WebTestRequest("http://testserver/website/products.aspx");
    request2.ThinkTime = 2;
    request2.QueryStringParameters.Add("CategoryID", "14", false, false);
    request2.PostRequest += new EventHandler(request2_PostRequest);
    yield return request2;

    WebTestRequest request3 = new WebTestRequest("http://testserver/website/products.aspx");
    request3.ThinkTime = 2;
    request3.QueryStringParameters.Add("CategoryID", "15", false, false);
    yield return request3;

    // Log this response out to a file, too

    WebTestRequest request4 = new WebTestRequest("http://testserver/website/products.aspx");
    request4.ThinkTime = 1;
    request4.QueryStringParameters.Add("CategoryID", "20", false, false);
    request4.PostRequest += new EventHandler(request4_PostRequest);
    yield return request4;
  }

  void request2_PostRequest(object sender, PostRequestEventArgs e)
  {
    File.WriteAllBytes("c:\\request2.html", e.Response.BodyBytes);
  }

  void request4_PostRequest(object sender, PostRequestEventArgs e)
  {
    File.WriteAllBytes("c:\\request4.html", e.Response.BodyBytes);
  }
粗粒度:表示类别级,即仅考虑对象的类别(the   type   of   object),不考虑对象的某个特定实例。比如,用户管理中,创建、删除,对所有的用户都一视同仁,并不区分操作的具体对象实例。  
细粒度:表示实例级,即需要考虑具体对象的实例(the   instance   of   object),当然,细粒度是在考虑粗粒度的对象类别之后才再考虑特定实例。比如,合同管理中,列表、删除,需要区分该合同实例是否为当前用户所创建。  
一般权限的设计是解决了粗粒度的问题,因为这部分具有通用性,而细粒度可以看成业务部分,因为其具有不确定性。

模拟 Web Javascrīpt
Web 测试引擎工作在 HTTP 层并且不运行 Javascrīpt。以影响 HTTP 层的方式依赖于 Javascrīpt 的 Web 站点,可使用编码的 Web 测试模拟通常由 Javascrīpt 执行的逻辑。例如下面一段JS
<scrīpt type="text/javascrīpt">
//get rid of some common non-digit characters
// in the phone number string function FixPhoneNumber()
{
var phoneNumberElement = document.getElementById(‘phoneNumber‘);
var number = phoneNumberElement.value;
number = number.replace(‘-‘, ‘‘);
number = number.replace(‘(‘, ‘‘);
number = number.replace(‘)‘, ‘‘);
number = number.replace(‘ ‘, ‘‘);
phoneNumberElement.value = number;
return true;
}
<div>
<input name="phoneNumber" id="phoneNumber" type="text"/>
<input name="submit" type="submit" value="Submit" ōnclick="FixPhoneNumber()" />
</div>
通过编程后
public override IEnumerator GetRequestEnumerator()
    {
      WebTestRequest request1 = new WebTestRequest("http://testserver/testwebsite/default.aspx");
      yield return request1;

      WebTestRequest request2 = new WebTestRequest("http://testserver/testwebsite/showparameters.aspx");
      request2.Method = "POST";
      FormPostHttpBody request2Body = new FormPostHttpBody();
     
      //get the databound phone number from the context and
      // strip out certain characters to simulate Javascrīpt
      string phoneNumber = this.Context["PhoneNumber"].ToString();
      phoneNumber = phoneNumber.Replace("-", "");
      phoneNumber = phoneNumber.Replace("(", "");
      phoneNumber = phoneNumber.Replace(")", "");
      phoneNumber = phoneNumber.Replace(" ", "");

      request2Body.FormPostParameters.Add("phoneNumber", phoneNumber);
      request2Body.FormPostParameters.Add("submit", "Submit");
      request2.Body = request2Body;
      yield return request2;
    }

运行并调试编码的Web 测试
对WebTest编程后,需要运行编码的WebTest,验证是否通过
在 Test View 或 Test Manager 窗口中选择该测试,并单击 Run 工具栏按钮
mamicode.com,码迷

转:创建编码的WebTest,码迷,mamicode.com

转:创建编码的WebTest

标签:style   blog   http   java   使用   os   

原文地址:http://www.cnblogs.com/lci05/p/3700069.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!