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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With