我正在尝试使用ExpectedException
中的C# UnitTest
属性,但我遇到了与我的特定Exception
一起使用的问题。这就是我得到的:
注意:我在行周边包裹着星号,这给我带来了麻烦。
[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块中,但是我想知道我是否能想出这种风格。
全部谢谢!
答案 0 :(得分:42)
除非异常类型与您在属性中指定的类型完全相同,否则它将失败 e.g
PASS: -
[TestMethod()]
[ExpectedException(typeof(System.DivideByZeroException))]
public void DivideTest()
{
int numerator = 4;
int denominator = 0;
int actual = numerator / denominator;
}
FAIL: -
[TestMethod()]
[ExpectedException(typeof(System.Exception))]
public void DivideTest()
{
int numerator = 4;
int denominator = 0;
int actual = numerator / denominator;
}
然而,这将通过......
[TestMethod()]
[ExpectedException(typeof(System.Exception), AllowDerivedTypes=true)]
public void DivideTest()
{
int numerator = 4;
int denominator = 0;
int actual = numerator / denominator;
}