nUnit Assert.That(方法,Throws.Exception)不捕获exception

有人能告诉我为什么这个unit testing检查exception失败吗? 显然,我真正的testing是检查其他代码,但我使用Int32.Parse来显示问题。

[Test] public void MyTest() { Assert.That(Int32.Parse("abc"), Throws.Exception.TypeOf<FormatException>()); } 

testing失败,给出这个错误。 很明显,我正在尝试testing这个exception,我想我的语法错过了一些东西。

 Error 1 TestCase '.MyTest' failed: System.FormatException : Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s) 

基于Throws Constraint(NUnit 2.5)的文档,

试试这个:

 Assert.That(() => Int32.Parse("abc"), Throws.Exception.TypeOf<FormatException>()); 

基本上你需要传递一个委托给Assert.That ,就像链接状态中的文档(注意,我在这里使用了lambdaexpression式,但它应该是相同的)。

你正在使用什么testing跑步者? 并不是所有的这些exception声明都能正确工作。

使用[ExpectedException (typeof(FormatException))]Assert.Throws<FormatException> (() => Int32.Parse("abc"));