在System.Windows.Forms中单元测试数据绑定

时间:2022-12-06 20:36:51

I'm facing a problem while unit testing my forms.

单元测试我的表单时遇到问题。

The problem is that data bindings are simply not working when the form is not visible.

问题是当表单不可见时,数据绑定根本不起作用。

Here's some example code:

这是一些示例代码:

Data = new Data();
EdtText.DataBindings.Add(
    new Binding("Text", Data, "Text", false, 
        DataSourceUpdateMode.OnPropertyChanged));

and later on:

后来:

Form2 f = new Form2();
f.Data.Text = "Test 1";
f.EdtText.Text = "Test 2";
f.Data.Text = "Test 3";

At the end the values for components are f.EdtText.Text = "Test 2" and f.Data.Text = "Test 3" but the expected values should be both "Test 3".

最后,组件的值是f.EdtText.Text =“Test 2”和f.Data.Text =“Test 3”,但是期望值应该都是“Test 3”。

Any suggestions?

1 个解决方案

#1


I think you answered your own question -- in order for the property change event (TextChanged) to occur the control has to be displayed. Your unit test can just do something like this:

我认为您回答了自己的问题 - 为了发生属性更改事件(TextChanged),必须显示控件。你的单元测试可以做这样的事情:

Form2 f = new Form2();
f.Show();
Thread.Sleep(2000); // give the Form time to open
f.Data.Text = "Test 1";
Assert.AreEqual("Test 1", f.EditText.Text);
f.Close();

Instead of exposing the Form components, you'll probably want to use NUnitForms to get the Form controls:

您可能希望使用NUnitForms来获取Form控件,而不是公开Form组件:

TextBoxTester tb = new TextBoxTester("EditText1");
Assert.AreEqual("Test 1", tb["Text"]);

#1


I think you answered your own question -- in order for the property change event (TextChanged) to occur the control has to be displayed. Your unit test can just do something like this:

我认为您回答了自己的问题 - 为了发生属性更改事件(TextChanged),必须显示控件。你的单元测试可以做这样的事情:

Form2 f = new Form2();
f.Show();
Thread.Sleep(2000); // give the Form time to open
f.Data.Text = "Test 1";
Assert.AreEqual("Test 1", f.EditText.Text);
f.Close();

Instead of exposing the Form components, you'll probably want to use NUnitForms to get the Form controls:

您可能希望使用NUnitForms来获取Form控件,而不是公开Form组件:

TextBoxTester tb = new TextBoxTester("EditText1");
Assert.AreEqual("Test 1", tb["Text"]);