Mar 4, 2012

How To Unit Test Async Methods with MSTest, XUnit and VS11 Beta

MSTest finally got some love with the Visual Studio 11 Beta and one of those changes was to enable tests to run asynchronously using the async and await keywords.

This is required if you want to write tests against any async methods (especially with WinRT!) but can also be used anywhere else you need to perform asynchronous operations.

Here’s a silly sample test to show you how it’s done

[TestMethod]
public async Task LoadGoogleHomePageAsync()
{
    var client = new System.Net.Http.HttpClient();
    var page = await client.GetStringAsync("www.google.com");
    Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Contains(page, "google");
}

XUnit also supports this option as shown here:

[Xunit.Fact]
public async Task XUnitAsyncTestMethod()
{
    var c = new System.Net.Http.HttpClient();
    var result = await c.GetStringAsync("http://www.google.com");
    Xunit.Assert.Contains("google", result);
}

Be aware that if you have a testsettings file specified in the Unit Test Explorer that async tests will not work.  This applies to the beta only.  Apart from that everything works as expected.

6 comments:

  1. Thanks- but your first example will not work- the URL string needs to include http://. Do you know if there is a mechanism for testing async void methods?

    ReplyDelete
  2. Your last paragraph just solved my problem! Thanks.

    ReplyDelete
  3. Limitation of not able to use async testmethod when testsettings is specified is fixed in RC build of VS2012.
    Async await in MSTest works fine in VS 2012 RC with or without testsettings file.

    ReplyDelete
  4. I'm not sure what's going wrong, it's not working for me. If I add an async test method, VS2012 doesn't list it as a runnable test.

    ReplyDelete
  5. If your test is not listed as a runnable test, you need to switch the test from void to Task.

    ReplyDelete
  6. I'm actually running into a similar issue with VS2012 my test run fine locally but give a UAT007 Not Runnable error on the server. The tests are all Task.

    ReplyDelete