gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:49:16 25 4
gpt4 key购买 nike

刚看完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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com