【问题标题】:Unit Testing ICommand with NSubstitute使用 NSubstitute 对 ICommand 进行单元测试
【发布时间】:2015-04-27 09:54:35
【问题描述】:

我有以下 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();
    }
}

IMyViewModel 定义为

public interface IMyViewModel
{
    ICommand MyCommand { get; }
} 

我的模型接口定义为

public interface IMyModel
{
    void SomeOtherCommand();
} 

现在在我的单元测试中(使用 NSubstitute),我想检查当 MyCommand 被调用时,我的模型收到了对其方法 SomeModelMethod 的调用。我试过了:

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

   viewModel.MyCommand.Execute(null);

   model.Received().SomeOtherMethod();
}

但这目前不起作用。当调用 ViewModel 上的命令时,如何最好地测试我的 Model 方法是否被调用?

【问题讨论】:

  • 与其为 viewModel 创建一个替代品,您可能更想做new viewModel(model.object) 或任何替代品。您不想模拟您实际测试的对象。

标签: wpf unit-testing nsubstitute


【解决方案1】:

不知道你为什么在这里嘲笑IMyViewModel。你说要测试在MyViewModel中执行命令时是否调用了SomeOtherMethod

你不应该在这里嘲笑MyViewModel

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

   viewModel.MyCommand.Execute(null);

   model.Received().SomeOtherMethod();
}

P.S:我不熟悉 nsubstitute。但是这个想法仍然是一样的(你不应该嘲笑 MyViewModel)。确保您在 nsubstitute 中使用了正确的方法。

【讨论】:

  • 谢谢,但是当试图调用 viewModel.MyCommand(null) 时,Visual Studio 现在大喊需要方法、委托或事件。我仍然不清楚如何正确调用 ICommand。有什么建议吗?
  • 哦。它应该是 viewModel.MyCommand.Execute(null) 谢谢
  • @JamesB 哈,我复制了你的代码并打了同样的错字:) 很高兴你解决了它。
猜你喜欢
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
  • 2014-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多