2013-08-29 60 views
3

我在單元測試中遇到了問題,我寫了一個行爲。該行爲如下:單元測試文本框行爲

NumericTextBoxBehavior : Behavior<TextBox> 
{ 
//handles few events like TextChanged ,PreviewTextInput , PreviewKeyDown , PreviewLostKeyboardFocus 
//to give make it accept numeric values only 

} 

雖然單元測試我寫了這個代碼

TextBox textBoxInvoker = new TextBox(); 
NumericTextBoxBehavior target = new NumericTextBoxBehavior(); 
System.Windows.Interactivity.Interaction.GetBehaviors(TextBoxInvoker).Add(target); 

現在提出我要叫

textBoxInvoker.RaiseEvent(routedEventArgs) 

此路由事件參數事件一樣轉爲路由事件作爲參數。

請幫助我如何創建mock RoutedEventArgs來提高事件並進一步單元測試的行爲。

在此先感謝。

回答

1

它可能會遲到,但這是一種單元測試行爲,它在調用鍵盤輸入時執行命令。

你可以找到更多信息herehere

[TestFixture] 
    public class ExecuteCommandOnEnterBehaviorFixture 
    { 
    private ExecuteCommandOnEnterBehavior _keyboardEnterBehavior; 
    private TextBox _textBox; 
    private bool _enterWasCalled = false; 


    [SetUp] 
    public void Setup() 
    { 
     _textBox = new TextBox(); 
     _keyboardEnterBehavior = new ExecuteCommandOnEnterBehavior(); 
     _keyboardEnterBehavior.ExecuteCommand = new Microsoft.Practices.Composite.Presentation.Commands.DelegateCommand<object>((o) => { _enterWasCalled = true; }); 
     _keyboardEnterBehavior.Attach(_textBox); 
    } 

    [Test] 
    [STAThread] 
    public void AssociatedObjectClick_Test_with_ItemClick() 
    { 
     _textBox.RaiseEvent(
     new KeyEventArgs(
      Keyboard.PrimaryDevice, 
      MockRepository.GenerateMock<PresentationSource>(), 
      0, 
      Key.Enter) { RoutedEvent = Keyboard.KeyDownEvent }); 

     Assert.That(_enterWasCalled); 
    } 
    }