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
XUnit also supports this option as shown here:
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.
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.