首页 > 解决方案 > 使用 Moq,为什么我不能在我的 Windows 窗体应用程序中引发和验证事件?

问题描述

我有一个 Windows 窗体应用程序,它在 Form_Load EventHandler 中设置了一个复选框的检查状态,当我运行该应用程序时它工作正常。但我还想要一个单元测试来验证事件是否将复选框设置为与预期的数据库值匹配。然而,在我的单元测试中,moq 框架.Raise似乎没有触发事件,因为我根本无法获得任何验证方法来通过。

这是代码:

表格1

public interface IForm1
{
    event EventHandler Load; //Assuming this exposes the Form's normal Load event to Test code
    void Form1_Load(object sender, EventArgs e);
    DataSet LoadData();
    CheckState MyCheckboxValue{ get;  set; }
}

表格1

public partial class Form1 : Form, IForm1
{
    public CheckState MyCheckboxValue
    {
        get => checkBox1.CheckState;
        set => checkBox1.CheckState = value;
    }

    public Form1()
    {
        InitializeComponent();

        this.Load += new System.EventHandler(this.Form1_Load);
    }

    public void Form1_Load(object sender, EventArgs e)
    {
        DataSet ds = LoadData();

        checkBox1.CheckState = ds.Tables[0].Rows[0]["IndicatorName"] == "Y" ? CheckState.Checked : CheckState.Unchecked;
    }

    public DataSet LoadData()
    {
        //Dumbing down real-world scenario of reading a value from database
        //For this demo code, lets dummy load 1 in-memory value
        var dt = new DataTable("");
        dt.Columns.Add("IndicatorName", typeof(string));
        dt.Rows.Add("Y");

        DataSet ds = new DataSet();
        ds.Tables.Add(dt);

        return ds;
    }
}

考试

public class Form1Should
{
    [Fact]
    public void SetCheckboxCheckedWhenDatasetIndicatorIsY()
    {
        // Arrange
        var dt = new DataTable("");
        dt.Columns.Add("CheckState", typeof(string));
        dt.Rows.Add("Y");

        DataSet m_ds = new DataSet();
        m_ds.Tables.Add(dt);

        var mockForm1 = new Mock<IForm1>();

        // Various attempts to do setups related to the event so verify tests below will work
        mockForm1.SetupAdd(m => m.Load += new System.EventHandler(mockForm1.Object.Form1_Load));
        mockForm1.Setup(x => x.Form1_Load(this, EventArgs.Empty)).Verifiable(); // I think Verifiable() is required to verify this method is called further below?
        mockForm1.Setup(x => x.LoadData()).Returns(m_ds);

        // Act 
        mockForm1.Raise(x => x.Load += null, this, EventArgs.Empty);

        //Assert - I can't get any of these to work:
        mockForm1.Verify(x => x.Form1_Load(It.IsAny<object>(), It.IsAny<EventArgs>()));
        mockForm1.Verify(x => x.LoadData());
        mockForm1.VerifyAdd(x => x.Load += It.IsAny<EventHandler>());
        mockForm1.VerifySet(x => x.MyCheckboxValue = CheckState.Checked, Times.Once);
    }
}

我究竟做错了什么?为什么.Raise没有效果?

标签: c#winformsunit-testingeventsmoq

解决方案


推荐阅读