lundi 27 avril 2015

Unit Testing ICommand with NSubstitute

I have the following ViewModel

public class MyViewModel : IMyViewModel
{
    private readonly IMyModel myMode;
    private ICommand _myCommand;

    public MyViewModel(IMyModel model)
    {
        _model = model;
    }

    public ICommand MyCommand
    {
        get { return _myCommand ?? (_myCommand = new RelayCommand(x => MyMethod())); }
    }

    private void MyMethod()
    {
        _model.SomeModelMethod();
    }
}

where IMyViewModel is defind as

public interface IMyViewModel
{
    ICommand MyCommand { get; }
} 

and my interface for the model is defined as

public interface IMyModel
{
    void SomeOtherCommand();
} 

Now in my unit test (using NSubstitute) I want to check that when MyCommand is invoked my model receives a call to its method SomeModelMethod. I've tried:

[TestMethod]
public void MyViewModel_OnMyCommand_CallsSomeOtherMethodOnModel()
{
   var model = Substitute.For<IMyModel>();
   var viewModel = Substitute.For<IMyViewModel>();

   viewModel.MyCommand(null);

   model.Received().SomeOtherMethod();
}

but this doesn't currently work. How do I best test that my Model method is called when a command on my ViewModel is invoked?

Aucun commentaire:

Enregistrer un commentaire