nUnit Assert.That(方法,Throws.Exception)没有捕获异常

时间:2010-03-25 15:04:19

标签: c# .net nunit exception

有人能告诉我为什么检查异常的单元测试失败了吗?显然,我真正的测试是检查其他代码,但我正在使用Int32.Parse来显示问题。

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

测试失败,发出此错误。显然我正在尝试测试这个异常,我想我的语法中缺少一些东西。

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)

的文档

2 个答案:

答案 0 :(得分:60)

请改为尝试:

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

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

答案 1 :(得分:9)

您使用的是什么样的跑步者?并非所有这些都与异常断言一起正常工作。

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

可能会有更好的运气