我正在编写单元测试来测试GUI中输入的数据是否经过验证和正确记录。目前我正在使用这样的代码:
using (MyControl target = new MyControl())
{
PrivateObject accessor = new PrivateObject(target);
TextBox inputTextBox = (TextBox)accessor.GetField("InputTextBox");
string expected, actual;
expected = "Valid input text.";
inputTextBox.Text = expected;
// InputTextBox.TextChanged sets FieldData.Input
actual = target.FieldData.Input;
Assert.AreEqual(expected, actual);
}
但我宁愿在TextChanged事件上使用Validated事件。
using (MyControl target = new MyControl())
{
PrivateObject accessor = new PrivateObject(target);
TextBox inputTextBox = (TextBox)accessor.GetField("InputTextBox");
string expected, actual;
bool valid;
expected = "Valid input text.";
inputTextBox.Text = expected;
valid = inputTextBox.Validate();
// InputTextBox.Validating returns e.Cancel = true/false
// InputTextBox.Validated sets FieldData.Input
Assert.IsTrue(valid);
actual = target.FieldData.Input;
Assert.AreEqual(expected, actual);
}
如何在文本框或支持Validated事件的任何其他控件上调用验证?我应该写什么代替inputTextBox.Validate()
?我对C#和VB.Net很满意。
答案 0 :(得分:3)
我不确定我是否在这里遗漏了一些内容,但这种扩展方法似乎有效:
private static readonly MethodInfo onValidating = typeof(Control).GetMethod("OnValidating", BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly MethodInfo onValidated = typeof(Control).GetMethod("OnValidated" , BindingFlags.Instance | BindingFlags.NonPublic);
public static bool Validate(this Control control)
{
CancelEventArgs e = new CancelEventArgs();
onValidating.Invoke(control, new object[] { e });
if (e.Cancel) return false;
onValidated.Invoke(control, new object[] { EventArgs.Empty });
return true;
}
并且被称为:
valid = inputTextBox.Validate();