c# - 使用 NUnit 和 C# 对异步方法进行单元测试

标签 c# unit-testing

我正在尝试对搜索查询的异步方法进行单元测试。单元测试定义如下:

[Test]
public async Task MyTest1()
{
    var readyToScheduleQuery = new ReadyToScheduleQuery()
    {
        Facets = new List<Facet>() 
                 {  
                     new Facet() 
                     {
                         Name = "Service Type", 
                         Values = new List<FacetValue>()
                                  {  
                                      new FacetValue() 
                                      {  
                                          Value = "SomeJob", 
                                          Selected = true
                                      } 
                                  } 
                     } 
                 }
    };

    var result = readyToScheduleQuery.ExecuteAsync(_appointmentRespositoryStub); 

    Assert.IsNotNull(result); 
}

readyToScheduleQuery 的ExecuteAsync 方法定义如下:

internal async Task<ReadyToScheduleResult> ExecuteAsync(IAppointmentRepository appointments)
{
    var query = await appointments.GetReadyToSchedule(this.Id, exclude: NotificationTags.Something);

单元测试只是挂起,永远不会返回结果。有任何想法吗?

如果我执行以下操作,它会挂断:(注意末尾的 Result 属性)

var result = readyToScheduleQuery.ExecuteAsync(_appointmentRespositoryStub).Result; 

最佳答案

您缺少等待。在编写 async/await 时,您会继续对所有标记为异步的所有内容调用 await,直至调用堆栈。

[Test]
public async Task MyTest1()
{
    var readyToScheduleQuery = new ReadyToScheduleQuery()
    {
        Facets = new List<Facet>() {  new Facet() {  Name = "Service Type", Values = new List<FacetValue>() {  new FacetValue() {  Value = "SomeJob", Selected = true} } } }                 
    };

    // missing await
    var result = await readyToScheduleQuery.ExecuteAsync(_appointmentRespositoryStub); 

    Assert.IsNotNull(result); // you will receive your actual expected unwrapped result here. test it directly, not the task.
}

这会挂起。

var result = readyToScheduleQuery.ExecuteAsync(_appointmentRespositoryStub).Result; 

参见 this previous answer Stephen Cleary 解释了为什么会这样。这里又是那个答案(请引用链接,以防它在写这个答案后发生变化)。

You're running into the standard deadlock situation that I describe on my blog and in an MSDN article: the async method is attempting to schedule its continuation onto a thread that is being blocked by the call to Result.

In this case, your SynchronizationContext is the one used by NUnit to execute async void test methods. I would try using async Task test methods instead.

关于c# - 使用 NUnit 和 C# 对异步方法进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36558094/

相关文章:

c# - 1053 Windows 服务错误使用 .NET Core 3.1 Worker 服务

c# - asp.net MVC JavaScript 调用 Controller

python - 使 pyunit 显示每个断言的输出

unit-testing - `go test` CLI 测试报告者的推荐

unit-testing - 寻找采用单元测试编码方法的好 Material

java - 创建这样的测试有意义吗?

c# - 如何配置 WebService 返回 ArrayList 而不是 Array?

c# - 周期性处理中的膨胀线程问题

c# - 如何取消共享共享打印机?

python - 更改由 nose 测试生成器创建的测试的名称