【问题标题】:How can I test a method with a Task return type?如何测试具有 Task 返回类型的方法?
【发布时间】:2015-05-07 06:35:08
【问题描述】:

我正在尝试测试签名格式为

的方法
public async Task<List<int>> MethodToBeTested()

我写了一个单元测试如下

[TestMethod] 
public async Task MethodToBeTestedSuccess()
{
Task<List<int>> results = await MethodToBeTested()
......
}

如果方法的返回类型是一个通用的整数列表,我会执行以下步骤来测试输出

List<int> results = MethodToBeTested();
int numberOfResults = results.Count;
Assert.AreEqual(numberOfResults,2300);

因此,我的问题是:如何测试 async 方法,它的返回类型包含在任务中,并验证是否返回了 2300 个结果?

如果我尝试在通用整数列表上尝试的策略,我会收到错误:无法将方法组 Count 转换为非委托类型 int。

提前感谢您的帮助。

【问题讨论】:

    标签: c# unit-testing async-await task


    【解决方案1】:

    假设单元测试框架是async-aware(如果你在做异步单元测试,希望它是:)),那么你应该能够修复你的编译器错误:

    [TestMethod] 
    public async Task MethodToBeTestedSuccess()
    {
        List<int> results = await MethodToBeTested()
        ......
    }
    

    换句话说,给定你显示的签名,那么如果你await方法调用,结果类型是List&lt;int&gt;,而不是Task&lt;List&lt;int&gt;&gt;,你应该声明变量以相应地接收结果。

    【讨论】:

      猜你喜欢
      • 2014-08-14
      • 1970-01-01
      • 2021-11-11
      • 2011-06-25
      • 2014-04-16
      • 2010-11-06
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多