Unit Testing the UI
by Jordan Vinarub

Listing One

public class Calculator : INotifyPropertyChanged
{
    public decimal Operand2
    {
        get { return _operand2; }
        set
        {
            if (value == _operand2)
                return;
            _operand2 = value;
            OnPropertyChanged("Operand2");
            OnPropertyChanged("CanDivide");
        }
    }
    public bool CanDivide
    {
        get { return (this.Operand2 != 0); }
    }
    ...
}

Listing Two
 
public partial class CalculatorForm : Form
{    
    public decimal Operand2
    {
        get { return Convert.ToDecimal(_operand2TextBox.Text); }
        set { _operand2TextBox.Text = value.ToString(); }
    }
    public bool CanDivide
    {
        get { return _divideButton.Enabled; }
        set { _divideButton.Enabled = value; }
    }
 ...
}


Listing Three
public partial class CalculatorForm : Form
{
    public CalculatorForm()
    {
        InitializeComponent();
        InitializeBindings();
        this.Calculator = new Calculator();
    }
    private void InitializeBindings()
    {      
        _divideButton.DataBindings.Add(
        "Enabled", _calculatorBindingSource, 
            "CanDivide", false,
             DataSourceUpdateMode.OnPropertyChanged);
        _operand2TextBox.DataBindings.Add(
            "Text", _calculatorBindingSource,
            "Operand2", false, DataSourceUpdateMode.OnPropertyChanged);
    }
 ...
}

Listing Four

public static class GUITester
{
    public static T FindControl<T>(Control container, string name)
          where T : Control
    {
        if (container is T && container.Name == name)
            return container as T;
        if (container.Controls.Count == 0)
            return null;
        foreach (Control child in container.Controls)
        {
            Control control = FindControl<T>(child, name);
            if (control != null)
                return control as T;
        }
        return null;
    }
}

Listing Five

[TestFixture]
public class CalculatorFormTest
{
    [Test]
    public void TestVisualizingOperand2()
    {
        CalculatorForm target = new CalculatorForm();
        target.Show();
        TextBox operand2TextBox =
           GUITester.FindControl<TextBox>(target, "_operand2TextBox");
        _target.Operand2 = 100;
        Assert.AreEqual(target.Operand2.ToString(),
            _operand2TextBox.Text);
        target.Close();
    }
}

Listing Six

[TestFixture]
public class CalculatorFormTest
{    
    [Test]
    public void TestBindingOperand2()
    {
        CalculatorForm target = new CalculatorForm();
        Calculator model = target.Calculator();
        target.Show();
        // Update the View and validate the model
        target.Operand2 = 7;
        Assert.AreEqual(target.Operand2, model.Operand2);
        // Update the model and validate the View
        model.Operand2 = 9;
        Assert.AreEqual(model.Operand2, target.Operand2);
        target.Close();
    }
}



3


