سؤال

I am having trouble in unit testing a behavior i wrote. The behavior is as follows:

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

}

While unit testing the same I wrote this code

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

Now to raise the event I have to call

textBoxInvoker.RaiseEvent(routedEventArgs)

this Routed event args in turn takes routed event as argument.

Please help me how to create mock RoutedEventArgs to raise the event and further Unit test the behavior.

Thanks in advance.

هل كانت مفيدة؟

المحلول

It may be late, but here is a way to unit test behavior which executes a command when Keyboard Enter was invoked.

You can find more information here and here

  [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);
    }
  }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top