In unit testing, there are times were the SUT has to be exercised asynchronously.
How can we wait for the exercise to complete execution?
The SpinWait synchronization type contains a method named SpinUntil which works perfect for the described scenario.
// Fixture setup
var sut = new ObjectLocalStorage();
sut.Set(@object, expected);
object result = null;
// Exercise system
new Task(() => result = sut.Get(@object)).Start();
SpinWait.SpinUntil(() => result != null);
// Verify outcome
Assert.Equal(expected, result);
// Teardown
Task
has been created it is immediately scheduled for execution by calling the Start
method.There is also a SpinUntil overload accepting a TimeSpan timeout.