我有一个依赖于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);
}
(请参见代码中的注释)
答案 0 :(得分: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能够设置任务结果。
设置结果后,就可以按照预期的方式等待任务,以验证预期的行为