2011-12-07 22 views
3

我正在編寫單元測試以測試在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); 
} 

如何在文本框或任何其他支持驗證事件的控件上調用驗證?我應該寫什麼來代替inputTextBox.Validate()?我對C#和VB.Net感到滿意。

回答

1

我不能肯定,如果我失去了一些東西,但這種擴展方法似乎工作:

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