Monday, November 02, 2009

ASP.NET, Master Pages and Selenium RC

Testing master pages in ASP.NET using Selenium can be tricky at the beginning since ASP.NET mangles the identifiers of controls on your pages. For example: You might have a form with an input text box. You give that text box the id 'myTextBox'. Then your Selenium RC test might look as follows:
[Test]
public void MyTextBox() {
   _selenium.Open("http://localhost:49583/");
   _selenium.Type("myTextBox", "some content");
   // ... rest of the test
}
The problem with this is that the test will fail even if you have given your textbox the correct id. The reason for that is that ASP.NET mangles the identifier to something like "ctl00_..._myTextBox". You can't be sure how it is mangled next time when you compile the page or next time ASP.NET is update. The better approach is one that works regardless how the id is mangled so long as the original id is still included. So here we go:
[Test]
public void MyTextBox() {
   _selenium.Open("http://localhost:49583/");
   _selenium.Type("//input[contains(@name, 'myTextBox')]", "some content");
   // ... rest of the test
}
Now of course you may need to locate an element more often so it makes sense to write a little method for this. With that method the test then becomes:
using csUnit;
using Selenium;

namespace MyWebSite.Web.Tests {
   [TestFixture]
   public class WebSiteTests {
      private string XPathForInput(string identifier) {
         return string.Format("//input[contains(@name, '{0}')]", identifier);
      }

      [Test]
      public void MyTextBox() {
         _selenium.Open("http://localhost:49583/");
         _selenium.Type(XPathForInput("myTextBox"), "some content");
         // ... rest of the test
      }

      // ... rest of the fixture

      private ISelenium _selenium;
   }
}
Although I found a few examples on the internet I thought that provide some concrete code might help you to get up to speed faster.

0 comments:

Post a Comment

All comments, questions and other feedback is much appreciated. Thank you!