Sometimes you have a simple page with some web controls on it.  You would like to have a simple way to make sure that the text of a status message is exactly the one you expect.  Well, it turns out that the .NET class library has a real gem that can help you.  The System.Net.WebClient class helps you request pages, post data, upload files with a simple interface.  Getting the page contents is easy:

[Test]
public void GetPage()
{
   WebClient client = new WebClient();
   using (Stream dataStream = client.OpenRead(pageAddress))
   {
      XmlDocument document = new XmlDocument();
      document.Load(dataStream);

      XmlNode label = document.SelectSingleNode("//label[@id='nameLabel']");
      Assert.AreEqual("Name:", label.InnerText);
   }
}

I have taken some extra care to return valid XML, so that I can get my label contents with a simple XPath expression.  You can use regexps or some ad-hoc parsing if you don't enjoy the luxury of XML output.

Posting values is not hard too.  I would like to simulate a button click, so that I can verify the Click event handler did exactly what I wanted it to do:

[Test]
public void PostValues()
{
   WebClient client = new WebClient();
   NameValueCollection values = new NameValueCollection();
   values["nameBox"] = "Ivan";
   values["saveButton"] = "Save";
   values["__EVENTTARGET"] = "saveButton";
   byte[] response = client.UploadValues(pageAddress, "POST", values);
   string html = System.Text.Encoding.UTF8.GetString(response);
 
   XmlDocument document = new XmlDocument();
   document.LoadXml(html);
   XmlNode message = document.SelectSingleNode("//span[@id='messageLabel']");
   Assert.AreEqual("Hi there", message.InnerText);
}

Posting the __EVENTTARGET parameter with the name of the button makes ASP.NET think the postback was triggered by the button.  It is essentially what the system __doPostback JavaScript function does.

Now that you get the general idea, please go to NUnitASP's home page and download the library.  It is an extension for NUnit that works in a similar way.  It exposes a clean tester API that will hide the tedious form post details from you.  It deals with plain HTML and does not require that you return valid XML from the server too.


rahnev
About the Author

Stefan Rahnev

Stefan Rahnev (@StDiR) is Product Manager for Telerik Kendo UI living in Sofia, Bulgaria. He has been working for the company since 2005, when he started out as a regular support officer. His next steps at Telerik took him through the positions of Technical Support Director, co-team leader in one of the ASP.NET AJAX teams and unit manager for UI for ASP.NET AJAX and Kendo UI. Stefan’s main interests are web development, agile processes planning and management, client services and psychology.

Related Posts

Comments

Comments are disabled in preview mode.