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
难道我们不需要围绕预期的违规代码尝试捕获预期的异常吗? –