Mã hoạt động tốt khi được gọi qua giao diện người dùng nhưng không hoạt động khi được gọi qua kiểm tra đơn vị. Tôi đã có thể repro này cho đơn giản Winform App.DataGridView không chấp nhận DataSource khi được gọi qua bài kiểm tra Đơn vị
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
}
}
}
mã kiểm tra Đơn vị
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.
}
}
}
mã sau đây được tạo ra bởi nhà thiết kế
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);
}
Tôi đoán là tôi đang thiếu một số loại cuộc gọi init trên đối tượng dataGridView1 trong đơn vị con đường mã kiểm tra . Nhưng việc sử dụng mã được thiết kế riêng trong thử nghiệm đơn vị không giúp ích gì. Điều này có liên quan đến đối tượng thực tế được liên kết với đối tượng Form
không?
Làm thế nào nó không thành công? –
@AustinSalonen dataGridView1.Rows.Count là 0. Nó phải là 2. – Ankush