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.

 

Reader Comments

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?

Your last paragraph just solved my problem! Thanks.

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.

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.

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

Post a Comment



Welcome

Thanks for dropping by. Enjoy your visit!

MVP Logo Visual Studio 2012 Cookbook
Find out more about Richard.

Richard on Twitter  
profile for Richard Banks on Stack Exchange, a network of free, community-driven Q&A sites

User Groups

My Open Source Projects

Podcast

Blog Archive