Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 测试DelegateCommand异步,无需公开处理程序_C#_Wpf_Mvvm_Prism - Fatal编程技术网

C# 测试DelegateCommand异步,无需公开处理程序

C# 测试DelegateCommand异步,无需公开处理程序,c#,wpf,mvvm,prism,C#,Wpf,Mvvm,Prism,使用Prism中的DelegateCommand无法再等待命令执行,因为FromAsynchHander已从版本6.3中删除 对于单元测试,建议如下所示进行移植,因此 Task MyHandler() {...} DelegateCommand myCommand = DelegateCommand.FromAsyncHandler(MyHandler); /// in test: await myCommand.Execute(); 换成 DelegateCommand myCommand

使用Prism中的DelegateCommand无法再等待命令执行,因为FromAsynchHander已从版本6.3中删除

对于单元测试,建议如下所示进行移植,因此

Task MyHandler() {...}
DelegateCommand myCommand = DelegateCommand.FromAsyncHandler(MyHandler);
/// in test:
await myCommand.Execute();
换成

DelegateCommand myCommand = new DelegateCommand(async () => await MyHandler());
/// in test:
await MyHandler();
但是,这需要将命令处理程序(MyHandler)公开,这否定了使用命令模式的封装好处

我知道我可以使用/创建其他命令实现,但我喜欢DelegateCommand,因为它是Prism的一部分,并且定期维护

是否有更好的方法使用DelegateCommand测试异步命令

是否有更好的方法使用DelegateCommand测试异步命令

不是真的。由于
DelegateCommand
类不公开任何异步和可等待的方法,因此恐怕您不能等待命令本身

您可以将
MyHandler()
方法
internal
应用于程序集:

[assembly: InternalsVisibleTo("UnitTests")] 

也许这样好一点。您的其他选择基本上是将方法
公开
或使用另一个支持
异步
/
等待
ICommand
实现,您对以下方法有何看法:

public class AsyncDelegateCommand : DelegateCommand
{
    private Func<Task> executeAction;

    public AsyncDelegateCommand(Func<Task> executeAction) : base(async () => { await executeAction(); })
    {
        this.executeAction =  executeAction;
    }

    public async Task ExecuteAsync()
    {
        if (CanExecute())
        {
            try
            {
                IsActive = true;
                await executeAction();
            }
            finally
            {
                IsActive = false;
            }
        }

        RaiseCanExecuteChanged();
    }
}

这正朝着正确的方向前进,将处理程序作为内部处理程序至少表明了我的意图。
await myCommand.ExecuteAsync();