Let's face it. Sometimes, the Microsoft. visualstudio. testtools. webtesting. htmldocument class does not cut it when you are writing custom extraction and verification rules. Htmldocument was originally designed as an internal class to effectively analyze URLs for subordinate requests (ratios) outside the HTML response body. Before VS 2005 RTM, we use htmldocument as a part of the public webtestframework API, but schedules and resource constraints prevent us from adding more common Dom functions such as innerhtml, innertext, and getelementbyid for it. You can analyze the HTML string by yourself,
Fortunately, there is another better option: htmlagilitypack.
Htmlagilitypack is an open-source project on codeplex. It provides standard DOM APIs and XPath navigation-even if HTML is not in the proper format!
The following is a web test example using htmlagilitypack. htmldocument to replace webtestframework. It simply verifies that the Microsoft homepage lists Windows as the first item in the navigation toolbar. Download htmlagilitypack and add a reference to it from your test project to try this encoding web test.
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 ";
}
}