如何对依赖于 TaskCompletionSource 的 class 进行单元测试?

How do I unit test a class that depends on TaskCompletionSource?

我有一个 class 依赖于 TaskCompletionSource

class 的示例如下所示:

public ExampleClass
{
    private TaskCompletionSource<string> _tcs;

    public async Task<string> GetFooAsync()
    {
        _tcs = new TaskCompletionSource<string>();
        return await _tcs.Task;
    }

    public void SetFoo(string value)
    {
        _tcs.SetResult(value);
    }
}

我正在使用 xUnit.net 作为我的测试框架。

[Fact]
public async Task ReturnsString()
{
    // Arrange
    const string value = "test";
    var myclass = new ExampleClass();

    // Act -- Does not work. I don't know how to fix this.
    var result = await myclass.GetFooAsync(); // Won't return before SetFoo is called
    myclass.SetFoo(value); // Needs to be run after GetFooAsync is called

    // Assert
    Assert.Equal(value, result);
}

(见代码注释)

对于这个例子,测试需要不同的安排

[Fact]
public async Task ReturnsString() {
    // Arrange
    const string expected = "test";
    var sut = new ExampleClass();

    var task = sut.GetFooAsync(); // launch tack and do not await
    sut.SetFoo(expected); // set expected value after GetFooAsync is called

    // Act
    var actual = await task;

    // Assert
    Assert.Equal(expected, actual);
}

任务可以启动而不是等待以允许 sut 能够设置任务结果。

设置结果后,即可按预期等待任务以验证预期行为