代码之家  ›  专栏  ›  技术社区  ›  Matt Norrie

测试delegatecommand async而不需要公开处理程序

  •  1
  • Matt Norrie  · 技术社区  · 6 年前

    使用 委派命令 在内部 棱镜 由于FromAsyncHanlder已从版本中删除,因此无法再等待命令执行 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测试异步命令?

    2 回复  |  直到 6 年前
        1
  •  2
  •   mm8    6 年前

    有没有更好的方法使用delegatecommand测试异步命令?

    不是真的。自从 DelegateCommand 类不公开任何异步和可等待的方法,恐怕不能等待命令本身。

    你可以做 MyHandler() 方法 internal 并应用 InternalsVisibleToAttribute 致您的大会:

    [assembly: InternalsVisibleTo("UnitTests")] 
    

    也许这样更好。你的其他选择基本上是 public 或者用另一个 ICommand 支持的实现 async / await 是的。

        2
  •  0
  •   Sergey    6 年前

    你对以下方法有何看法:

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