If you’re trying to do unit testing using async functions in Visual Studio 2012, you may be in for a surprise.

For example, lets start with a very simple test project like this:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;

namespace UnitTestProject1
{
    [TestClass]
    public class MyAwesomeTestClass
    {
        [TestMethod]
        public void MyAwesomeTest()
        {
            int a = 0;
            a += 10;
            Assert.AreEqual(a, 10);
        }
    }
}

Nice and simple.

When I run the test, I am greeted with a pleasant green checkmark:

Unit tests pass. Horay.

Now I’m going to make a small change to the test above:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;

namespace UnitTestProject1
{
    [TestClass]
    public class MyAwesomeTestClass
    {
        [TestMethod]
        public async void MyAwesomeTestAsync()
        {
            int a = 0;
            await Task.Run(() => a += 10);
            Assert.AreEqual(a, 10);
        }
    }
}

All I’ve done is changed the code to run the add operation asynchronously. Now when I go to the run the tests, the Test Explorer window gives a not-so-pleasant message:

Build your solution to discover all available 
tests. Click "Run All" to build, discover, and run 
all tests in your solution.

So what gives?

It turns out that if you want to unit test an asynchronous method, it needs to return a “Task” object. There are no warnings from Visual Studio. You’re just supposed to “know.”

Change the code to this:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;

namespace UnitTestProject1
{
    [TestClass]
    public class MyAwesomeTestClass
    {
        [TestMethod]
        public async Task MyAwesomeTestAsync()
        {
            int a = 0;
            await Task.Run(() => a += 10);
            Assert.AreEqual(a, 10);
        }
    }
}

And lo and behold:

Unit tests pass again. All is well.

The checkmark we love so dearly returns.