该代码在通过 UI 调用时工作正常,但在通过单元测试调用时不起作用。我能够为简单的 Winform App 重现这个。
namespace WinFormApp
{
public class Pair
{
public string Key { get; set; }
public string Value { get; set; }
}
public class FormManager
{
List<Pair> _source = new List<Pair>()
{
new Pair() { Key="1", Value = "one" },
new Pair() { Key = "2", Value = "two" }
};
public FormManager(DataGridView dgv)
{
dgv.DataSource = _source;
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
FormManager manager = new FormManager(dataGridView1); // This works
}
}
}
单元测试代码
namespace WinFormApp.Test
{
[TestClass()]
public class FormManagerTest
{
private DataGridView dataGridView1;
[TestMethod()]
public void FormManagerTestSource()
{
this.dataGridView1 = new System.Windows.Forms.DataGridView();
FormManager target = new FormManager(dataGridView1);
Assert.AreEqual(2, dataGridView1.Rows.Count); // This fails.
}
}
}
以下代码由设计师生成
private void InitializeComponent()
{
this.dataGridView1 = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(20, 27);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.Size = new System.Drawing.Size(240, 150);
this.dataGridView1.TabIndex = 0;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.dataGridView1);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
}
我的猜测是我在单元测试代码路径中缺少对 dataGridView1 对象的某种初始化调用。但是在单元测试中使用设计器生成的代码并没有帮助。这与与对象关联的实际对象有关Form
吗?