gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:18:09 32 4
gpt4 key购买 nike

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

[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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com