OscarXie.net

关注质量与体验——电子商务与自动化测试

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

 让我们面对它,有时候,当您正在编写自定义的提取和验证规则时Microsoft.VisualStudio.TestTools.WebTesting.HtmlDocument 类不会剪切它。HtmlDocument最初设计是作为一个内部类非常有效地为HTML响应正文之外的从属请求(比如图像)分析URLs。VS 2005 RTM 之前,我们将HtmlDocument 作为公有WebTestFramework API的一部分,但是时间安排和资源约束阻止我们为其添加更多的常规目的 DOM 功能如InnerHtml、InnerText 和GetElementById。您可以自己分析HTML字符串,不过

幸运的是还有一个更好的选择:HtmlAgilityPack

HtmlAgilityPack 是CodePlex 上的一个开源项目。它提供了标准的DOM API 和XPath 导航--即使 HTML 不是适当的格式!

 下面是使用HtmlAgilityPack.HtmlDocument代替WebTestFramework中的Web测试示例。它简单验证微软主页在导航工具条上将Windows列为第一项。下载HtmlAgilityPack 并从您的测试项目添加对它的引用来尝试此编码 Web 测试。

using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.VisualStudio.TestTools.WebTesting;

using HtmlAgilityPack;

public class WebTest1Coded : WebTest

{

public override IEnumerator<WebTestRequest> GetRequestEnumerator()

{

WebTestRequest request1 = new WebTestRequest("http://www.microsoft.com/");

request1.ValidateResponse += new EventHandler<ValidationEventArgs>(request1_ValidateResponse);

yield return request1;

}

void request1_ValidateResponse(object sender, ValidationEventArgs e)

{

//load the response body string as an HtmlAgilityPack.HtmlDocument

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();

doc.LoadHtml(e.Response.BodyString);

//locate the "Nav" element

HtmlNode navNode = doc.GetElementbyId("Nav");

//pick the first <li> element

HtmlNode firstNavItemNode = navNode.SelectSingleNode(".//li");

//validate the first list item in the Nav element says "Windows"

e.IsValid = firstNavItemNode.InnerText == "Windows";

}

}

                          JoshCh发布于星期天,2006年12月10日下午9点56分

原文地址:http://blogs.msdn.com/joshch/archive/2006/12/10/be...

posted on 2007-11-14 20:47  oscarxie  阅读(1486)  评论(0编辑  收藏  举报