c# - 如何等待异步命令进行单元测试?

标签 c# multithreading unit-testing async-await icommand

我正在尝试对命令进行单元测试,但由于它是异步命令,因此测试方法会在命令完成之前进入断言。我已经查找了这个问题的解决方案,他们都在谈论创建一个我不想做的 AsyncCommand 接口(interface)等,因为我只需要等待用于单元测试目的的命令。那么是否有另一种更简单且不需要创建另一个接口(interface)等的解决方案?

这是我的命令类:

   public class Command : ICommand
    {
        public void Execute(object parameter)
        {
          //exeute...
        }

        //other stuff....
    }

那是经过测试的类(class):
pubic class MyClass
{
    private Command commandForTest;
    public Command CommandForTest
            {
                get
                {
                    if (commandForTest == null)
                    {
                        commandForTest = new Command(async (o) =>
                        {
                            if(someCondition)
                               await SomeMethod();
                             else
                               await AnotheMrthod();   

                        });
                    }
                    return commandForTest;
                }
            }
}

这是测试方法:
[TestMethod]
        public async Task Test()
{
    MyClass myclass = new MyClass();
    await Task.Run( () =>  myclass.CommandForTest.Execute());
    //Assert....
}

最佳答案

So is there another solution to this which is simpler and doesn't require creating another interface etc?



不,是的。还有另一种解决方案。是不是 更简单。最简单直接的解决方案是使用 IAsyncCommand interface .或 AsyncCommand您的单元测试可以强制转换 ICommand 的实现到(更脆)。

但是如果你想走硬路线,那么是的,你可以在技术上检测到 async void方法完成。您可以通过编写自己的 SynchronizationContext and listening to OperationStarted and OperationCompleted 来做到这一点。 .您还需要构建一个工作队列并编写一个处理队列的主循环。

我有一种可以做到这一点的类型。它被称为 AsyncContext and it is part of AsyncEx .用法:
[TestMethod]
public void Test() // note: not async
{
  MyClass myclass = new MyClass();
  AsyncContext.Run(() =>
  {
    myclass.CommandForTest.Execute();
  });
  //Assert....
}

同样,我强烈建议使用 IAsyncCommand .真正的问题是核心 MVVM 类型不足。所以大多数人使用IAsyncCommandMvxAsyncCommandAsyncCommand或将命令逻辑公开为 async Task VM 上的方法。

关于c# - 如何等待异步命令进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56425469/

相关文章:

c# - c#中的另一个进程正在使用文件

c# - 如何在 EF Core 多对多关系中对删除进行建模?

multithreading - 多少线程太多了?

python - 试图断开玩家

java - 多线程环境下 LinkedList<T> clear 和 new LinkedList<T> 的区别

javascript - `screen` 带来什么值(value)?

c# - 使用泛型实现类型安全的枚举模式

c# - 为什么我的表单在调用 BeginConnect 时卡住?

java - 如何从 JMockit 模拟静态方法

Python 模拟 requests.get 内容和 iter_lines()