18
我正在嘗試使用C# UnitTest
中的ExpectedException
屬性,但我遇到了問題,無法使用我的特定Exception
。這是我得到的:ExpectedException屬性用法
注意:我纏着星號繞着那條給我麻煩的線。
[ExpectedException(typeof(Exception))]
public void TestSetCellContentsTwo()
{
// Create a new Spreadsheet instance for this test:
SpreadSheet = new Spreadsheet();
// If name is null then an InvalidNameException should be thrown. Assert that the correct
// exception was thrown.
ReturnVal = SpreadSheet.SetCellContents(null, "String Text");
**Assert.IsTrue(ReturnVal is InvalidNameException);**
// If text is null then an ArgumentNullException should be thrown. Assert that the correct
// exception was thrown.
ReturnVal = SpreadSheet.SetCellContents("A1", (String) null);
Assert.IsTrue(ReturnVal is ArgumentNullException);
// If name is invalid then an InvalidNameException should be thrown. Assert that the correct
// exception was thrown.
{
ReturnVal = SpreadSheet.SetCellContents("25", "String Text");
Assert.IsTrue(ReturnVal is InvalidNameException);
ReturnVal = SpreadSheet.SetCellContents("2x", "String Text");
Assert.IsTrue(ReturnVal is InvalidNameException);
ReturnVal = SpreadSheet.SetCellContents("&", "String Text");
Assert.IsTrue(ReturnVal is InvalidNameException);
}
}
我有ExpectedException
捕獲的基本類型Exception
。這不應該照顧它嗎?我曾嘗試使用AttributeUsage
,但它也沒有幫助。我知道我可以把它包裝在一個try/catch塊中,但是我想看看我能否把這個風格弄清楚。
謝謝大家!
工程就像一個魅力,感謝您的解釋。這是一些簡單的代表,歡呼! – Jonathan
我不會鼓勵 [TestMethod的()] [的ExpectedException(typeof運算(System.Exception的),AllowDerivedTypes =真)] 出於同樣的原因,我不鼓勵 ... 趕上(異常前) {... – Mick
難道我們不需要圍繞預期的違規代碼嘗試捕獲預期的異常嗎? –