【问题标题】:Which unit test will force to write the next asynchronous C# code?哪个单元测试将强制编写下一个异步 C# 代码?
【发布时间】:2017-10-06 02:00:48
【问题描述】:

在这个链接here上,有一个关于如何在c#中编写异步方法的建议,即:

using System.Threading.Tasks;
...
void Foo(){}
...
new Task(Foo).Start();

我的问题是关于如何将 TDD 方法应用于该代码,确切地说:我应该编写哪个单元测试来强制编写以前的代码。

谢谢:)

【问题讨论】:

  • 应该编写异步方法(尤其是访问外部资源的方法),以便您可以像这样使用它:await Foo(),而无需手动启动任务。
  • 为了强制编写异步函数,只需断言返回值的类型为TaskTask<T>
  • 这是一个老问题/答案,(只是)在 async/await 可用之前

标签: c# unit-testing asynchronous tdd


【解决方案1】:

我认为您必须问问自己您实际测试的是什么?在您提供的示例中:

void Foo(){}

Foo 只是类上的一个方法,因此您将创建一个测试来测试 Foo 的功能,它与为异步代码编写测试无关。

但是,如果 Foo 的返回类型为 TaskTask<T>,您可以执行以下操作。

给定班级:

public class Bar
{
    public Task<string> Foo()
    {
        Console.WriteLine("foo called");
        return Task.FromResult("123");
    }
}

测试将如下所示:

[TestClass]
public class BarTest
{

    [TestMethod]
    public async Task Test_Foo()
    {
        // Arrange
        var bar = new Bar();

        // Act
        var result = await bar.Foo();

        // Assert
        Assert.AreEqual("123", result);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-15
    • 2013-06-02
    • 2014-09-29
    • 2016-02-23
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多