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?
source to share