.net - 我应该对 View 模型上的方法或命令进行单元测试吗?

标签 .net wpf mvvm viewmodel view-model-pattern

刚看完Jason Dolinger's video on MVVM ,我想澄清一下如何正确设置和单元测试我的 View 模型的 ICommand 属性。

考虑以下带有 FooBarCommand ICommandProperty 的 ViewModel 类。

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();
    }
}

因此,如果我对 ViewModel 的 FooBar 功能进行单元测试,我可以通过调用 testVM.FooBar() 或通过调用 testVM.FooBarCommand.Execute() 执行命令来运行 FooBar()。哪个是首选?我倾向于测试 FooBarCommand 属性,因为最终 View 上的按钮被绑定(bind)到 FooBarCommand 属性而不是 FooBar() 方法。

另外,由于我的 View 将绑定(bind)到 IViewModel 而不是 ViewModel,我应该能够完全从 IViewModel 接口(interface)中省略 FooBar() 方法吗?

最佳答案

为什么不使用 DelegateCommand 或 RelayCommand?如果你这样做,你就不必问这个问题,因为只有 Comand 本身是公共(public)的——那么 canexecute 和 execute 方法是私有(private)的。

我们只需要对公共(public)的东西进行单元测试。

ps:不要错过我对您问题的评论,请直接在您的 View 模型中使用 IMessageBoxService 而不是 MessageBox。

关于.net - 我应该对 View 模型上的方法或命令进行单元测试吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11465068/

相关文章:

wpf - MVVM - WPF : Updating view model boolean property when TextBox is being edited

android - 如何在MVVM中重试API调用

c# - 一个类怎么可能没有构造函数呢?

c# - WPF Databinding DataTrigger 根据 bool 值改变形状的颜色

c# - 是否有 "String.Format"可以接受命名输入参数而不是索引占位符?

wpf - 全局设置 View 模型

c# - 具有参数的WPF Mvvm导航

wpf - TreeView 绑定(bind)到 View 模型不起作用

.net - 将 IDisposable 作为参数传递

c# - 控制台应用程序中的消息泵