April 14, 2005

Window Driver - a .Net perspective

Testing is goodness. Writing tests for the data access layer and business object layer are commonplace and sometimes even generated! However, testing UI components has often been more difficult to accomplish; screen scraping and tracking mouse clicks dissappoints. Inspired by Mr. Fowler's article, Window Driver, I attempted to do something similiar for my current project.

First, I took the ultra-simple approach of making the controls public, and then accessing them from the unit test code. However, this implement breaks encapsulation and feels 'dirty'. John suggested Reflection. Reflection is good clean fun, so I started down that path, and then realized, that every class that derives from System.Windows.Forms.Control (Form, UserControl...) exposes a public controls collection! so................


[Test]
public void MyUITest()
{
MyForm form = new MyForm();
ComboBox combo1 = GetControl(form, "combo1") as ComboBox;
Assert.IsNotNull(combo1);
Assert.AreEqual(combo1.SelectedValue, "somevalue");

//TODO party on the combo1 control
}

private Control GetControl(Control parent, string name)
{
foreach(Control c in parent.Controls)
{
if(name == c.Name)
return c;
}
return null;
}


So, hopefully this helps and inspires someone else! Test first baby!

jk

1 comment:

Brian Lounsberry said...

SendKeys to the rescue! ;)