I recently had to write unit tests for asynchronous operations – specifically, files being downloaded off the internet. But how do you write a test which checks the result of an async operation? You can’t just subscribe to some XxxCompleted event and do Asserts there because your test runner would have exited the test method by then.
The solution? Block the test method:
[TestFixture]
public class MyTests
{
private ManualResetEvent waitHandle;
[Test]
public void TestAsyncPageDownloading()
{
waitHandle = new ManualResetEvent(false);
⋮
wdp.GetWebDataCompleted += wdp_GetWebDataCompleted;
wdp.GetWebDataAsync(new Uri("http://nesteruk.org/blog"), new object());
waitHandle.WaitOne(); // blocks unit tests until asserts run
}
void wdp_GetWebDataCompleted(object sender, GetWebDataCompletedEventArgs e)
{
StreamReader sr = new StreamReader(e.Stream);
string s = sr.ReadToEnd();
Console.WriteLine("Here's what we got:");
Console.WriteLine(s);
// the following assert will be called by the test runner
Assert.Contains(s, "Dmitri", "My webpage should have my name.");
waitHandle.Set(); // unblocks unit test
}
}
Maybe there’s a better way to do this, though?