bitwix

Tangential comments about Software Development

Friday, May 09, 2008

Just enough to test a Windows UI

Here's just enough code to test a Windows Form. Put this in a Class Library project called Tests which references the DLL or EXE with the form in. The Tests project will need to reference System.Windows.Forms.

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Dunwoody;
using NUnit.Framework;

namespace Tests
{
[TestFixture]
public class UITests
{
Form1 m_f;
[SetUp]
public void SetUp()
{
m_f = new Form1();
m_f.Show();
}
[TearDown]
public void TearDown()
{
m_f.Dispose();
m_f = null;
}

[Test]
public void RequiredWidgets()
{
Assert.AreEqual( "", HasWidgets(new string[] {
"button1", "textbox1"
}));
}

private string HasWidgets(string[] ctrlnames )
{
StringBuilder result = new StringBuilder();
foreach (string ctrlname in ctrlnames)
{
if (GetControl(ctrlname) == null)
result.Append(ctrlname + " ");
}
return result.ToString().Trim();
}

[Test]
public void HasButton()
{
Button b = GetButton( "button1" );
Assert.IsNotNull(b);
}
[Test]
public void NoSuchButton()
{
Assert.IsNull(GetButton("x"));
}
[Test]
public void TextboxNotButton()
{
Assert.IsNotNull(GetControl("textbox1"));
Assert.IsNull(GetButton("textbox1"));
}
[Test]
public void HasTextbox()
{
Assert.IsNotNull(GetTextbox("textbox1"));
}
[Test]
public void SetTextbox()
{
string test = "Test";
GetTextbox("textbox1").Text = test;
Assert.AreEqual(test, GetTextbox("textbox1").Text);
}
[Test]
public void ButtonClick()
{
string test = "Test";
string str = GetTextbox("textbox1").Text;
GetTextbox("textbox1").Text = test;
GetButton("button1").PerformClick();
Assert.AreEqual("[" + test + "]", GetTextbox("textbox1").Text);
}

private TextBox GetTextbox(string ctrlname)
{
Control ctrl = GetControl(ctrlname);
if (ctrl != null)
return ctrl as TextBox;
return null;
}

private Button GetButton(string ctrlname )
{
Control ctrl = GetControl(ctrlname);
if (ctrl != null)
return ctrl as Button;
return null;
}

private Control GetControl(string ctrlname)
{
foreach (Control ctrl in m_f.Controls)
if (String.Compare(ctrlname.Trim(), ctrl.Name, true) == 0)
return ctrl;
return null;
}
}
}