I have a class that depends on TaskCompletionSource
An example of the class looks like this:
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);
}
}
I am using xUnit.net as my testing framework.
[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);
}
(see comments in code)
For this example case, the test needs to be arranged differently
[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);
}
The task can be launched and not awaited to allow for the sut to be able to set the task result.
Once the result is set, the task can then be awaited as intended to verify the expected behavior