单元测试控制行为

Unit testing a control behaviour

在我的 C# 项目中,我有一个获取 Control 并清除其中内容的方法。

public static void ClearText(Control con)
    {
        foreach (Control c in con.Controls)
        {
            if (c is TextBox)
                ((TextBox)c).Clear();
            else if (c is ComboBox)
            {
                if (((ComboBox) c).DataSource != null)
                    ((ComboBox) c).DataSource = null;
                else
                    ((ComboBox) c).Items.Clear();
            }
            else if (c is CheckBox)
                ((CheckBox) c).Checked = false;
            else
                ClearAllText(c);
        }
    }

此代码工作正常,现在我正在尝试为其创建一些单元测试。我试过这条路,似乎没问题:

这意味着参考 Windows.Forms,有什么办法可以做到这一点吗?也许使用某种方式 Mocking ?

鉴于您问题中的示例代码,我认为编写单元测试来执行此实用程序函数没有任何问题。没有任何需要模拟框架的具体内容。

[TestMethod]
public void WhenClearingTextOnAControl_AndControlContainsNestedCheckboxes_ShouldClearCheckedBoxes()
{
    // arrange: create a control hierarchy
    var input = new Panel();
    var insidePanel = new Panel();
    var checkbox = new Checkbox();
    input.Controls.Add(insidePanel);
    insidePanel.Controls.Add(checkbox);
    checkbox.Checked = true;

    // act: invoke our function
    _subject.ClearText(input);

    // assert
    Assert.IsFalse(checkbox.Checked, "Inner checkbox should have been cleared.");
}