2015-11-24 29 views
31

我剛剛在.NET Framework上使用測試工具,所以我在ReSharper的幫助下從NuGet下載了它。nUnit中的ExpectedException給了我一個錯誤

我使用這個Quick Start來學習如何使用nUnit。我剛剛複製的代碼和錯誤想出了這個屬性:

[ExpectedException(typeof(InsufficientFundsException))] //it is user defined Exception 

的錯誤是:

類型或命名空間名稱「的ExpectedException」找不到 (是否缺少使用指令或裝配參考?)

爲什麼?如果我需要這樣的功能,我應該用什麼替換它?

+0

顯示什麼錯誤?錯誤是在nUnit還是IDE中顯示的? – Chawin

+0

我認爲你的代碼返回一個異常,它不是InsufficientFundsException –

回答

54

如果你使用的是NUnit 3.0,那麼你的錯誤是因爲ExpectedExceptionAttributehas been removed。你應該使用像Throws Constraint這樣的結構。

例如,你鏈接的教程有這個測試:

[Test] 
[ExpectedException(typeof(InsufficientFundsException))] 
public void TransferWithInsufficientFunds() 
{ 
    Account source = new Account(); 
    source.Deposit(200m); 

    Account destination = new Account(); 
    destination.Deposit(150m); 

    source.TransferFunds(destination, 300m); 
} 

要改變這種NUnit的3.0下工作,將其更改爲以下:

[Test] 
public void TransferWithInsufficientFunds() 
{ 
    Account source = new Account(); 
    source.Deposit(200m); 

    Account destination = new Account(); 
    destination.Deposit(150m); 

    Assert.That(() => source.TransferFunds(destination, 300m), 
       Throws.TypeOf<InsufficientFundsException>()); 
} 
4

如果你仍然想使用屬性,考慮這個:

[TestCase(null, typeof(ArgumentNullException))] 
[TestCase("this is invalid", typeof(ArgumentException))] 
public void SomeMethod_With_Invalid_Argument(string arg, Type expectedException) 
{ 
    Assert.Throws(expectedException,() => SomeMethod(arg)); 
} 
11

不知道這是否最近改變,但與NUnit 3.4.0它提供Assert.Throws<T>

[Test] 
public void TransferWithInsufficientFunds() { 
    Account source = new Account(); 
    source.Deposit(200m); 

    Account destination = new Account(); 
    destination.Deposit(150m); 

    Assert.Throws<InsufficientFundsException>(() => source.TransferFunds(destination, 300m)); 
} 
相關問題