简体   繁体   English

使用NSubstitute对ICommand进行单元测试

[英]Unit Testing ICommand with NSubstitute

I have the following ViewModel 我有以下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 IMyViewModel被定义为

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 . 现在,在单元测试中(使用NSubstitute),我想检查当MyCommand调用时,我的模型是否收到对其方法SomeModelMethod的调用。 I've tried: 我试过了:

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

   viewModel.MyCommand.Execute(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? 在ViewModel上调用命令时,如何最好地测试是否调用了Model方法?

Not sure why you're mocking IMyViewModel here. 不知道为什么在这里嘲笑IMyViewModel You said you wanted to test whether SomeOtherMethod is invoked when you execute the command in MyViewModel . 您说过要测试在MyViewModel执行命令时是否调用SomeOtherMethod

You shouldn't be mocking the MyViewModel here. 您不应该在这里嘲笑MyViewModel

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

   viewModel.MyCommand.Execute(null);

   model.Received().SomeOtherMethod();
}

PS: I'm not familiar with nsubstitute. PS:我不熟悉nsubstitute。 But the idea is still same (you shouldn't mock MyViewModel). 但是想法还是一样的(您不应该嘲笑MyViewModel)。 Make sure you're using the right methods in nsubstitute. 确保在nsubstitute中使用正确的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM