2012-03-08 38 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