2017-10-19 129 views
1

我使用Visual Studio附帶的測試框架以及NSubstitute來單元測試一個需要系統ID的方法,並在系統找不到時引發異常在數據庫中...NSubstitute:Assert不包含拋出的定義

public VRTSystem GetSystem(int systemID) 
{ 
    VRTSystem system = VrtSystemsRepository.GetVRTSystemByID(systemID); 
    if (system == null) 
    { 
    throw new Exception("System not found"); 
    } 
    return system; 
} 

(在這種情況下,似乎很奇怪,有一個具體的商業案例這種方法需要它拋出一個異常,爲返回一個空系統不接受其使用)

我想編寫一個測試來檢查系統不存在時是否引發異常。目前,我有以下...

[TestMethod] 
public void LicensingApplicationServiceBusinessLogic_GetSystem_SystemDoesntExist() 
{ 
    var bll = new LicensingApplicationServiceBusinessLogic(); 
    try 
    { 
    VRTSystem systemReturned = bll.GetSystem(613); 
    Assert.Fail("Should have thrown an exception, but didn't.); 
    } 
    catch() { } 
} 

通過不嘲諷庫,通過VrtSystemsRepository.GetVRTSystemByID()返回的將是無效的制度,引發的異常。雖然這有效,但對我來說卻是錯誤的。我不希望在測試中需要try/catch塊。

NSubstitute docs有暗示我應該可以測試這個如下的例子...

[TestMethod] 
public void GetSystem_SystemDoesntExist() 
{ 
    var bll = new LicensingApplicationServiceBusinessLogic(); 
    Assert.Throws<Exception>(() => bll.GetSystem(613)); 
} 

但是,如果我嘗試這在我的測試代碼,我得到Throws以紅色突出顯示,與錯誤消息「斷言不包含定義拋出

現在,我沒有真正確定該網頁上的樣本覆蓋我的情況下,作爲測試代碼指定所測試的方法拋出一個異常,這我不明白,因爲我認爲這個想法的測試是單獨測試該方法,並測試在各種情況下會發生什麼。但是,即使沒有這一點,我不明白爲什麼Assert.Throws方法不存在。

任何任何想法?

編輯: DavidG指出Assert.Throws可能是NUnit的一部分,而不是MS框架,這將解釋爲什麼它不被識別。如果是這樣,我目前正在測試正確的方式來做到這一點?

+1

您正在使用哪種測試框架? 'Assert.Throws'可能是NUnit。 – DavidG

+0

@DavidG啊,忘了補充一點,對不起。我正在使用VS附帶的MS。我會更新這個問題。 –

+1

DavidG提到的@AvrohomYisroel引用的文檔使用NUnit進行斷言。如果不使用該框架,則可以使用['ExpectedExceptionAttribute Class'](https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.expectedexceptionattribute.aspx) – Nkosi

回答

2

正如DavidG所述引用的文檔使用NUnit進行斷言。

如果不使用該框架可以使用ExpectedExceptionAttribute Class

[TestMethod] 
[ExpectedException(typeof(<<Your expected exception here>>))] 
public void GetSystem_SystemDoesntExist() { 
    var bll = new LicensingApplicationServiceBusinessLogic(); 
    bll.GetSystem(613); 
} 

如果預期沒有拋出異常這將失敗。

+1

更好的是,添加一個AssertThrows()方法,它更加簡潔。有關信息,請參閱此MSDN頁面https://msdn.microsoft.com/library/jj159340.aspx#sec18 –

相關問題