Wednesday, January 23, 2013

Testing async Methods in C# 5

Last week I promised that I’d write a blog post on using Assert.ThrowsException() to test async methods. Before I get to that, let’s go over some of the other issues that come up with testing async methods.

First, let’s look at a test to verify that an async method works correctly:


public async Task<string> GetMessage(string user)
     return await Task.FromResult(string.Format(“Hello {0}”, user));


One test that works could be written like this:


public void SimplePathTest()
    var worker = new Worker();
    var answer = worker.GetMessage(“unit tests”).Result;
    Assert.AreEqual(“Hello, unit tests”, answer);


I don’t like writing tests like that.  Calling “.Result” on a task is a code smell.  The test method blocks until the result is available. That’s probably OK in a test method (more on that in future blog posts), but I’m still concerned. Developers often copy code from unit tests into production code. (I’ve done it myself when I’m learning how a library works.)  For that reason, I want my unit tests for follow the practices I would use in production code. That means I want to ‘await’ the result, not block for it.

Read more: SRT Solutions
QR: Inline image 1

Posted via email from Jasper-Net