以编程方式对 TextBox 调用验证

Han*_*ood 5 .net validation invoke winforms

我正在编写单元测试来测试在 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);
}
Run Code Online (Sandbox Code Playgroud)

但我宁愿使用 Validated 事件而不是 TextChanged 事件。

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);
}
Run Code Online (Sandbox Code Playgroud)

如何在文本框或支持 Validated 事件的任何其他控件上调用验证?我应该写什么来代替inputTextBox.Validate()?我对 C# 和 VB.Net 很满意。

Han*_*ood 4

我不确定我是否在这里遗漏了一些东西,但这个扩展方法似乎有效:

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;
}
Run Code Online (Sandbox Code Playgroud)

并通过以下方式调用:

valid = inputTextBox.Validate();
Run Code Online (Sandbox Code Playgroud)