I just finished watching Jason Dolinger's video on MVVM, and I'd like some clarification on how to properly setup and unit test the ICommand properties of my view models.
Consider the following ViewModel class with a FooBarCommand ICommandProperty.
public class ViewModel : IViewModel
{
public ICommand FooBarCommand { get; private set; }
public bool CanExectuteFooBar()
{
return true;
}
public void FooBar()
{
//Do some FooBarish stuff
}
}
public interface IViewModel
{
void FooBar();
System.Windows.Input.ICommand FooBarCommand { get; }
}
public class FooBarCommand : ICommand
{
private ViewModel vm;
public FooBarCommand(ViewModel vm)
{
this.vm = vm;
}
public bool CanExecute(object parameter)
{
return vm.CanExectuteFooBar();
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
vm.FooBar();
}
}
So if I'm unit testing the FooBar functionality of ViewModel I could run FooBar() either by calling testVM.FooBar() or by executing the command by calling testVM.FooBarCommand.Execute(). Which is preferred? I'm leaning towards testing the FooBarCommand property, because ultimately the buttons on the view are being bound to the FooBarCommand property not the FooBar() method.
In addition, since my View will be bound to an IViewModel not a ViewModel, I should be able to omit the FooBar() method from the IViewModel interface entirely correct?
why dont you use DelegateCommand or RelayCommand? if you would do that you wouldnt have to ask this question because just the Comand itself is public - the canexecute and execute methods are private then.
and we just have to unittest public stuff.
ps: dont miss my comment on your question, use a IMessageBoxService instead of MessageBox directly in your viewmodels.