Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically invoking validation on a TextBox

I'm writing unit tests to test whether data typed in the GUI is validated and recorded correctly. Currently I'm using code like this:

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);
}

But I would rather use the Validated event over the TextChanged event.

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);
}

How can I invoke validation on a text box, or any other control that supports the Validated event? What should I write in place of inputTextBox.Validate()? I'm comfortable with C# and VB.Net.

like image 515
Hand-E-Food Avatar asked Oct 09 '22 07:10

Hand-E-Food


1 Answers

I'm not certain if I'm missing something here, but this extension method appears to work:

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;
}

And is called with:

valid = inputTextBox.Validate();
like image 193
Hand-E-Food Avatar answered Oct 13 '22 11:10

Hand-E-Food