c# - 使用 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
没有效果?
解决方案
推荐阅读
- nuke-build - NUKE CI 构建错误“已添加具有相同密钥的项目”
- texture-mapping - Meshlab 在编辑面和导出到 DAE 时不保留纹理映射
- python - 如何在 PyQt5 的不同类中调用 QCheckBox?
- python - 有没有办法将一列十六进制代码传递到 Matplotlib/seaborn?
- java - Quarkus:包含未处理异常的堆栈跟踪
- python - Pandas 比较不同时间段的客户支出
- powershell - Onedrive 处理 OneDrive 文件夹中文件的动态 URL 路径以用作 Power Apps 数据表中的链接的明显问题
- excel - 使用类/标签名称提取数据并限制结果
- python - 如何在python中选择声音设备
- ruby-on-rails - 评论文章应用程序中 Ruby on Rails 中模型的未定义方法