如何对TaskCompletionSource进行单元测试?

问题描述 投票:0回答:1

如何对TaskCompletionSource进行单元测试?

我的班级看起来像这样:

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
c# unit-testing xunit.net taskcompletionsource
1个回答
0
投票

对于此示例情况,测试需要以不同的方式安排

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

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

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

可以启动任务而不必等待任务,以使sut能够设置任务结果。

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

© www.soinside.com 2019 - 2024. All rights reserved.