简体   繁体   English

哪个单元测试将强制编写下一个异步C#代码?

[英]Which unit test will force to write the next asynchronous C# code?

On this link here , a recommendation is made on how to write a async method in c#, which is: 此处的此链接上,提出了有关如何使用c#编写异步方法的建议,即:

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

My question is about how to apply a TDD approach to that code, exactly: which unit test I should write to force the writing of the previous code. 我的问题是关于如何将TDD方法准确地应用于该代码:我应该编写哪个单元测试以强制编写先前的代码。

Thanks :) 谢谢 :)

I think you have to ask yourself what you're actually testing? 我认为您必须问自己,您正在实际测试什么? In the example you provided: 在示例中,您提供了:

void Foo(){}

Foo is just a method on class so you would create a test that tests the functionality of Foo and it has nothing to do with writing tests for async code. Foo只是类上的一种方法,因此您将创建一个测试Foo功能的测试,并且与编写异步代码测试无关。

However if Foo had a return type of Task or Task<T> you could do the following. 但是,如果Foo的返回类型为TaskTask<T> ,则可以执行以下操作。

Given the class: 给定班级:

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

The test would then look like: 该测试将如下所示:

[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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM