【问题标题】:nUnit Assert.That(method,Throws.Exception) not catching exceptionsnUnit Assert.That(method,Throws.Exception) 没有捕获异常
【发布时间】:2011-01-31 18:39:40
【问题描述】:

谁能告诉我为什么这个检查异常的单元测试会失败?显然,我真正的测试是检查其他代码,但我使用 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)的文档

【问题讨论】:

  • 您也可以这样做:Assert.Throws&lt;FormatException&gt;(() =&gt; Int32.Parse("abc"));
  • 我试图在这个项目中坚持使用 Assert.That 风格。不过,我不像以前那样依恋它了。

标签: c# .net nunit exception


【解决方案1】:

您使用的是什么测试运行器?并非所有这些都与异常断言一起正常工作。

使用[ExpectedException (typeof(FormatException))] 甚至Assert.Throws&lt;FormatException&gt; (() =&gt; Int32.Parse("abc")); 可能会有更好的运气

【讨论】:

  • 我使用的是 TDD.net 和 nUnit gui。您的修复有效,但我想使用流利的语法。我给了你一点帮助!
  • 我知道这是一个旧答案,当时是正确的。但是对于现在和将来的参考,ExpectedException 属性在 NUnit 3.0 上已弃用:github.com/nunit/docs/wiki/Breaking-Changes
【解决方案2】:

试试这个:

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

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

【讨论】:

  • 啊,我不得不让一个匿名代表...我现在在文档中看到了,只是不是很清楚。谢谢!
  • 如果有人发现他们的匿名函数返回 void,您需要执行以下操作:Assert.That(new Action(() =&gt; VoidReturningMethod("abc")), Throws.Exception.TypeOf&lt;FormatException&gt;());
  • 感谢 @MartinNeal 帮助我走上了正确的道路,但对我来说它抱怨它必须是一个 TestDelegate,所以我不得不这样做:new TestDelegate(() =&gt; AddBlockingTaskToBox())
猜你喜欢
  • 1970-01-01
  • 2021-06-20
  • 2013-03-24
  • 2013-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
相关资源
最近更新 更多