Chapter 11. Unit Testing Async Code
I’d like to look briefly at how to unit test async code. The simplest approach doesn’t work well, but it can be easy to write good tests that call async methods, depending on support from your unit test framework.
The Problem with Unit Testing in Async
Async methods return quickly, usually returning a Task that completes at some point in the future.
To consume them, we’d normally use await, so let’s experiment with that approach in
a unit test.
[TestMethod]publicasyncvoidAlexsTest(){intx=awaitAlexsMethod();Assert.AreEqual(3,x);}
To allow us to use await, I’ve
also marked my test method async. But
that has a very important side effect. Now, the test method also returns
quickly and completes at some point in the future. In fact, the test
method returned without throwing any exceptions as soon as it reaches the
await, so the test framework, in this
case MSTest, marks it as a pass.
Because the test method is async
void, any exceptions that happen in it are rethrown on the
calling SynchronizationContext, where
they are either ignored, or cause an unrelated future test to fail.
The real danger here is that all your tests will appear to pass, irrespective of the actual result.
Writing Working Async Tests Manually
One way to avoid this problem is to avoid making your test methods async. Instead, we have to wait synchronously for the result of any async calls they make.
[TestMethod]publicvoidAlexsTest(){intx=AlexsMethod().Result;Assert.AreEqual ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access