2013-04-10 75 views
1

我使用xUnit和FluentAssertions來編寫我的單元測試,我被困在以下問題。由於我還沒有執行WebExceptioncatchGetCountriesAsync),所以我在這裏扔了一個新的NotImplementedException尋找這個單元測試的更好的實現

這段代碼是我做了如預期測試實際工作的唯一途徑。我添加了原生xUnit實現,因爲FluentAssertions只是語法糖。

[Fact] 
public async Task GetCountriesAsyncThrowsExceptionWithoutInternetConnection() 
{ 
    // Arrange 
    Helpers.Disconnect(); // simulates network disconnect 
    var provider = new CountryProvider(); 

    try 
    { 
     // Act 
     var countries = await provider.GetCountriesAsync(); 
    } 
    catch (Exception e) 
    { 
     // Assert FluentAssertions 
     e.Should().BeOfType<NotImplementedException>(); 

     // Assert XUnit 
     Assert.IsType<NotImplementedException>(e); 
    } 
} 

雖然我發現這個實現更好,但它不工作。

[Fact] 
public async Task GetCountriesAsyncThrowsExceptionWithoutInternetConnection3() 
{ 
    // Arrange 
    Helpers.Disconnect(); // simulates network disconnect 
    var provider = new CountryProvider(); 

    // Act/Assert FluentAssertions 
    provider.Invoking(async p => await p.GetCountriesAsync()) 
      .ShouldThrow<NotImplementedException>(); 

    // Act/Assert XUnit 
    Assert.Throws<NotImplementedException>(async() => await provider.GetCountriesAsync()); 
} 

作爲VS2012/ReSharper的已經表明,以除去測試方法的冗餘async關鍵字,我取代async Taskvoid和測試仍行爲相同,所以我懷疑異步Action s不能被期待已久的,他們被解僱並被遺忘。

是否有妥善的xUnit/FluentAssertions實現這個辦法?我想我必須去我的第一個實施,因爲我看不到任何功能,如InvokingAsync()

+0

可能重複[如何處理xUnit .net的Assert.Throws中的任務引發的異常?](http://stackoverflow.com/questions/14084923/how-to-handle-exceptions-thrown-by-tasks -in-xunit-nets-assert-throwst) – 2013-04-10 14:21:20

+0

非常好,正是我在尋找的東西。謝謝! – 2013-04-10 14:52:49

回答

0

關於FluentAssertions,我已經添加了以下我的代碼:

using System; 
using System.Threading.Tasks; 

namespace FluentAssertions 
{ 
    public static class FluentInvocationAssertionExtensions 
    { 
     public static Func<Task> Awaiting<T>(this T subject, Func<T, Task> action) 
     { 
      return() => action(subject); 
     } 
    } 
} 

,現在你可以這樣做:

_testee.Awaiting(async x => await x.Wait<Foo>(TimeSpan.Zero)) 
     .ShouldThrow<BarException>(); 

_teste.Wait<T>回報Task<T>。 方法Awaiting的命名也是有意義的,因爲純粹的方法調用不會導致異常被調用者捕獲,所以您需要使用await來執行此操作。

相關問題