【问题标题】:Unit Test Prism 5 async Delegatecommand executes in parallelUnit Test Prism 5 async Delegatecommand 并行执行
【发布时间】:2014-10-24 23:49:57
【问题描述】:

我正在为具有 DelegateCommand 的 ViewModel 编写单元测试。该命令使用异步方法执行,自 Prism 5 起支持如下:

MyCommand = new DelegateCommand(async () => await MyMethod());

现在我进行了单元测试,我注意到,

await model.Command.Execute();
Assert.IsTrue(model.CommandWasRun); // just an example

在命令运行时立即返回(因此失败)。

我认为这是一个错误的原因是,如果我写的话,在同一个单元测试中一切都很好

await model.MyMethod();
Assert.IsTrue(model.CommandWasRun);

是我遗漏了什么还是这是一个错误?

【问题讨论】:

    标签: c# unit-testing async-await .net-4.5 prism-5


    【解决方案1】:

    您不能在DelegateCommand 构造函数中使用async 委托。你必须使用FromAsyncHandler:

    MyCommand = DelegateCommand.FromAsyncHandler(async () => await MyMethod());
    

    或者,等效地:

    MyCommand = DelegateCommand.FromAsyncHandler(() => MyMethod());
    

    【讨论】:

    • 谢谢 - 就是这样。我只是查看了 DelegateCommand 的来源并且不明白,为什么他们不只是添加另一个接受 Func 的构造函数,而不是使用改变您使用 DelegateCommand 的 Factorymethod...
    • 有没有办法在没有 lambda 表达式的情况下提供该方法?如果不是,为什么需要 lambda 表达式。我想了想:MyCommand = DelegateCommand.FromAsyncHandler(MyMethod);
    • @MarkusWeber:您应该能够通过方法组。我没试过。
    猜你喜欢
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 2016-03-15
    • 2016-08-02
    • 1970-01-01
    相关资源
    最近更新 更多