Today, I was trying to create a WatiR test for my login page. I was using the LoginControl hence the UserName and Password TextBox was embedded inside the LoginControl. My first reaction was to create a BetterFindControl method so I can access the TextBoxes. So, I came up with the following code:
public static T BetterFindControl<T>(this Element root, string id) where T : Element
{
if (root != null)
{
if (root.Id == id) return root as T;
var foundControl = (T)root.FindControl<T>(id);
if (foundControl != null) return foundControl;
foreach (Element childControl in root.DomContainer.Elements)
{
foundControl = (T)BetterFindControl<T>(childControl, id);
if (foundControl != null) return foundControl as T;
}
}
return null;
}
Unfortunately, the code ended up consuming too much memory and the application got hung up. Next, I used regular expression to access the control.
[Test]
public void should_be_able_to_find_username_textbox_inside_login_control()
{
using (IE ie = new IE(Pages.Default_Url))
{
ie.TextField(new Regex("UserName")).TypeText("john");
ie.TextField(new Regex("Password")).TypeText("johndoe");
ie.Button(new Regex("LoginButton")).Click();
Assert.AreEqual(Pages.Home_Page_Url, ie.Url);
}
}
This technique worked but it is little shaky since now I cannot have a different parent control in the page having the TextBox named "UserName". Anyway, the regular expression technique worked in my scenario. I wish the WatiN Framework had the smart FindControl or FindElement method to recursively find nested controls.