How can I write a test for WPF command binding?

I have a "commands" class:

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

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

      

Code in MainWindow.xaml.cs file:

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 custom control that implements the menu bar:

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

      

The code works. I like the general pattern and would like to keep using it.

However, I also try to pursue some other goals such as doing Test Driven Development and achieving 100% coverage by my module and integration tests. I would also like to be 100% consistent with StyleCop and FxCop warnings. And I was caught here.

My MainWindow.Exit()

method is private as recommended by FxCop (Microsoft.Security:CA2109), but that means I cannot call it directly from the test. I suppose I could make it public and suppress the FxCop message. Or I can use an accessory. But I have a bias towards writing tests directly against private methods, especially in this case, since all it does is a method test, 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 is working as intended (besides testing it manually). Any suggestions?

+2


source to share


2 answers


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

You can call commands from code with this:



ICommand command = ExitCommand;

command.Execute();

      

This will execute Exit () and require no access. Is this what you were looking for?

+5


source


Using a split view pattern like MVVM will allow you to test most of your code, including logical commands. The views then become much simplified and less important to the unit test. I suggest you familiarize yourself with MVVM and related patterns.



0


source







All Articles