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.
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?
ReplyDeleteYour last paragraph just solved my problem! Thanks.
ReplyDeleteLimitation of not able to use async testmethod when testsettings is specified is fixed in RC build of VS2012.
ReplyDeleteAsync 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.
ReplyDeleteIf your test is not listed as a runnable test, you need to switch the test from void to Task.
ReplyDeleteI'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