Jon*_*han 24 c# unit-testing exception expected-exception
我正在尝试使用a中的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);
}
}
Run Code Online (Sandbox Code Playgroud)
我有ExpectedException基本类型Exception.这不应该照顾它吗?我尝试过使用AttributeUsage,但也没有帮助.我知道我可以将它包装在try/catch块中,但是我想知道我是否能想出这种风格.
谢谢大家!
Mic*_*ick 47
除非异常类型与您在属性中指定的类型完全相同,否则它将失败
通过:-
[TestMethod()]
[ExpectedException(typeof(System.DivideByZeroException))]
public void DivideTest()
{
int numerator = 4;
int denominator = 0;
int actual = numerator / denominator;
}
Run Code Online (Sandbox Code Playgroud)
失败:-
[TestMethod()]
[ExpectedException(typeof(System.Exception))]
public void DivideTest()
{
int numerator = 4;
int denominator = 0;
int actual = numerator / denominator;
}
Run Code Online (Sandbox Code Playgroud)
然而,这将通过......
[TestMethod()]
[ExpectedException(typeof(System.Exception), AllowDerivedTypes=true)]
public void DivideTest()
{
int numerator = 4;
int denominator = 0;
int actual = numerator / denominator;
}
Run Code Online (Sandbox Code Playgroud)