1

我有一门课取决于TaskCompletionSource

该类的一个示例如下所示:

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

(见代码中的注释)

4

1 回答 1

1

对于这个示例案例,测试需要以不同的方式安排

[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 能够设置任务结果。

一旦设置了结果,就可以按预期等待任务以验证预期的行为

于 2019-10-07T11:27:27.523 回答