2012-03-08 73 views
1

我仍然在.NET 4.0中,我想知道这种模式是否将保持良好的各种异步单元测试情况:MsTest与Task.ContinueWith()和Task.Wait()...?

/// <summary> 
/// Noaa weather test: should read remote XML. 
/// </summary> 
[TestMethod] 
public void ShouldReadRemoteXml() 
{ 
    var uri = new Uri("http://www.weather.gov/xml/current_obs/KLAX.xml"); 
    var wait = HttpVerbAsyncUtility.GetAsync(uri) 
     .ContinueWith(
     t => 
     { 
      Assert.IsFalse(t.IsFaulted, "An unexpected XML read error has occurred."); 
      Assert.IsTrue(t.IsCompleted, "The expected XML read did not take place."); 

      if(t.IsCompleted && !t.IsFaulted) 
       FrameworkFileUtility.Write(t.Result, @"NoaaWeather.xml"); 
     }) 
     .Wait(TimeSpan.FromSeconds(7)); 

    Assert.IsTrue(wait, "The expected XML read did not take place within seven seconds."); 
} 

请问这个Task.ContinueWith()...Task.Wait()模式在现实世界中托起?我是比较新的正式思考单元测试(特别是异步单元测试),所以请不要憋在基础:)

+1

完整的源代码工作的任何最终的解决方案?也许更复杂的示例用于在每个线程中通知错误,WaitAll显示摘要后? – Kiquenet 2014-01-01 10:56:20

+0

@Kiquenet所有你要求的东西应该是开箱即用的;我认为MSTest中的异步支持不在那里,所以XUnit可能是另一种选择[http://sravi-kiran.blogspot.com/2012/11/UnitTestingAsynchronousMethodsUsingMSTestAndXUnit.html] – rasx 2014-01-03 00:03:05

回答

10

单元测试框架通常不使用异步代码开箱即用的工作非常好,这是我们非常关心的,因为我们将await添加到C#和Visual Basic。

通常会发生什么是测试方法打第一个“等待”,这立即返回。该测试然后被标记为已成功,因为它没有错误地返回,即使在继续中将产生错误。

我们正在与单元测试框架供应商合作,以改善这个故事的Visual Studio即将发布的版本。 MSTest和XUnit.NET现在可以在VS 11 Beta中正确处理异步方法。我的建议是:获得ahold of the VS 11 beta并在其中尝试异步单元测试支持。如果你不喜欢它,现在将是一个伟大的时间give that feedback on the async forum