tags:

views:

115

answers:

2

I have a "commands" class:

public static class MyCommands
{
    private static ICommand exitCommand = new RoutedCommand();

    public static ICommand ExitCommand { get { return exitCommand; } }
}

Code-behind in MainWindow.xaml.cs:

private void BindCommands()
{
    this.CommandBindings.Add(new CommandBinding(MyCommands.ExitCommand, this.Exit));
}

private void Exit(object sender, ExecutedRoutedEventArgs e)
{
    Application.Current.Shutdown();
}

And some XAML in a user control that implements a menu bar:

<MenuItem Header="_Exit"
          Command="{x:Static local:MyCommands.ExitCommand}"
          />

The code works. I like the general pattern involved and I'd like to continue using it.

However, I am also trying to pursue some other goals, such as doing Test Driven Development and achieving 100% coverage with my unit and integration tests. I'd also like to have 100% conformance with StyleCop and FxCop warnings. And I'm caught here.

My MainWindow.Exit() method is private, as recommended by FxCop (Microsoft.Security:CA2109), but this means I can't call it directly from a test. I suppose I could make it public and suppress the FxCop message. Or I can use an accessor. But I have a bias against writing tests directly against private methods, especially in this case since all that does is test the method and not the command binding itself.

I feel like there must be some other way to invoke the command from my test code so that I can verify that the command works as intended (besides testing manually). Any suggestions?

A: 

Using a separated presentation pattern such as MVVM will allow you to test the bulk of your code, including the logic behind commands. The views then become greatly simplified and less critical to unit test. I suggest you read up on MVVM and related patterns.

HTH, Kent

Kent Boogaart
My code-behind event handlers will mostly be one-liners -- either simple UI logic (as in the example) or API methods on model code. I also plan to use injection dependency so I can mock things like Application.Current and verify that Shutdown() got called.But I can't figure out how to trigger the Command so that my event handler gets run during my test. Like I said, I could use an accessor to call the private method, but I'd really like to use the Commanding system to verify automatically that everything is wired together correctly.
mcl
A: 

I realize this is an old question, but I figured I'd answer in case it helps anyone else.

You can invoke commands from code-behind with this:

ICommand command = ExitCommand;

command.Execute();

It only uses public methods, and does not require an accessor. It will execute Exit(). Is this what you were looking for?

mattjf