2016-03-01 39 views
0

我需要編寫一個測試來驗證創建一個對象並傳入空參數會拋出一個ArgumentNullExceptionNUnit拋出的正確語法

這是我有:

[Test] 
public void ThrowsOnNullDependency() 
{ 
    Assert.Throws(() => new FileService(null), Throws.Exception.TypeOf<ArgumentNullException>()); 
} 

而且,我發現了以下情況除外。我見過幾個不同的網站,所以似乎都使用NUnit的不同功能和語法。用NUnit3檢查是否引發異常的正確方法是什麼?

CS1503參數2:不能從「NUnit.Framework.Constraints.ExactTypeConstraint」轉換爲「NUnit.Framework.TestDelegate」

CS1660無法轉換lambda表達式爲類型「IResolveConstraint」,因爲它不是委託鍵入

+0

你爲什麼不的ExpectedException屬性添加到測試方法 – Gurpreet

+0

,因爲這是在NUnit的2移除我正在使用NUnit 3. – user9993

+1

爲了澄清事情,[ExpectedException屬性](http://www.nunit.org/index.php?p=exception&r=2.5)_was_存在於NUnit 2.x中,但已被刪除在NUnit 3中 – stuartd

回答

2

如果你只是想檢查異常被拋出,那麼無論這些將工作:

Assert.Throws<ArgumentNullException>(() => new FileService(null)); 

Assert.Throws(typeof(ArgumentNullException),() => new FileService(null)); 

如果你想使用ThrowsConstraint for more control over the check,然後你用Assert.That與約束語法將是這樣的:

Assert.That(() => new FileService(null), Throws.TypeOf<ArgumentNullException>()); 
+0

http://stackoverflow.com/q/15014461/2903863 – Gurpreet