C# MVVMLight RelayCommand.RaiseCannexecutechanged don';t引发CanExecuteChanged事件

C# MVVMLight RelayCommand.RaiseCannexecutechanged don';t引发CanExecuteChanged事件,c#,wpf,mvvm-light,relaycommand,C#,Wpf,Mvvm Light,Relaycommand,我正在用WPF和MVVMLight框架开发一个应用程序 我正在尝试进行单元测试(我是这方面的新手)。因此,我尝试通过订阅命令上的CanExecuteChanged事件来模拟视图,并验证是否正确调用了该事件。但是当我这样做的时候,它永远不会被调用,即使我调用了RaiseCanExecuteChanged方法 下面是一个非常简单的示例: bool testCanExec = false; var testCmd = new RelayCommand( exe

我正在用WPF和MVVMLight框架开发一个应用程序

我正在尝试进行单元测试(我是这方面的新手)。因此,我尝试通过订阅命令上的CanExecuteChanged事件来模拟视图,并验证是否正确调用了该事件。但是当我这样做的时候,它永远不会被调用,即使我调用了RaiseCanExecuteChanged方法

下面是一个非常简单的示例:

bool testCanExec = false;
var testCmd = new RelayCommand(
                     execute:    () => { System.Diagnostics.Debug.WriteLine($"Execute call"); },
                     canExecute: () => { System.Diagnostics.Debug.WriteLine($"CanExecute call"); return testCanExec; }
                );
testCmd.CanExecuteChanged += ((sender, args) => { System.Diagnostics.Debug.WriteLine($"CanExecuteChanged call"); });
testCanExec = true;
testCmd.RaiseCanExecuteChanged(); // <= nothing in output
testCmd.Execute(null);            // <= output: "CanExecute call", "Execute call"
bool testCanExec=false;
var testCmd=new RelayCommand(
execute:()=>{System.Diagnostics.Debug.WriteLine($“execute call”);},
canExecute:()=>{System.Diagnostics.Debug.WriteLine($“canExecute调用”);返回testCanExec;}
);
testCmd.CanExecuteChanged+=((发送方,参数)=>{System.Diagnostics.Debug.WriteLine($“CanExecuteChanged调用”);});
testCanExec=true;

testCmd.RaiseCanExecuteChanged();//
RelayCommand
raisecannexecutechanged
方法只调用
CommandManager.invalidateRequestSuggested()
,在单元测试上下文中无效:

…因为没有控件订阅了
CommandManager.RequerySuggested
事件

此外,通常不应该编写测试第三方框架功能的单元测试。您可能应该专注于测试自己的自定义功能

但是如果您想测试
CanExecute
方法,只需调用它,而不是引发
CanExecuteChanged
事件:

bool b = testCmd.CanExecute(null);  

感谢您的解释。事实上,我不想测试MVVMLight框架,我只是想确保CanExecuteChanged事件正确引发,因为CanExecute方法使用许多其他属性,所以每次更改其中一个字段时,我都必须调用RaiseCanExecuteChanged方法。