1

I have an application that I am building unit tests for. For certain operations, I use ApplicationCommands (eg. ApplicationCommands.New). Is there an easy way to call CanExecute and Execute on a routed UI command in the unit test? I thought about implementing a mock IInputElement, but that seems like a lot of work. Is there a better way?

[TestMethod]
public void NewDocument()
{
     Assert.IsTrue(ApplicationCommands.New.CanExecute(null, mockTarget));
     ApplicationCommands.New.Execute(null, mockTarget);
     Assert.IsTrue(workspace.OpenDocuments.Count == 1);
}

It looks like this is very similar to this question why-does-my-command-canexecute-always-return-false-in-unit-test? Does anyone know of a way to execute the routed ui command without the ui actually being there?

I have the command and command binding, but I don't know how to create the command source and command target.

Community
  • 1
  • 1
travis
  • 233
  • 3
  • 11

1 Answers1

0

You should be testing the actual ICommand class that responds to the routed command. If this routed command is implemented just by event handlers in one of you code-behind files, then I'd suggest pulling an ICommand out of those and testing that.

Testing that the command is routed properly is not a unit test you should be writing. Instead that should be an integration test that could be done with coded UI testing via Visual Studio (or some other GUI test framework).

Patrick Quirk
  • 23,334
  • 2
  • 57
  • 88
  • I don't actually have a command in my view model. I have a `CommandBinding` and a `CommandBindingCollection`. The collection is what I use in the xaml. If I try to test the `ICommand` object out of the routed UI command binding, `CanExecute` is always false. – travis Jan 15 '14 at 21:30
  • That's what I was getting at with my second sentence. Your code isn't very unit-testable set up how you have it. In order for the routed command to work, your entire view needs to be created and run in a WPF environment since that is what hooks up the command to the binding. If you pull out the `CanExecute`/`Execute` handlers into a command object, it's much easier to test. – Patrick Quirk Jan 16 '14 at 02:12