nUnit Assert.That(method,Throws.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)
基于 抛出约束 (NUnit 2.5) 的文档
Can someone tell me why this unit test that checks for exceptions fails? Obviously my real test is checking other code but I'm using Int32.Parse to show the issue.
[Test]
public void MyTest()
{
Assert.That(Int32.Parse("abc"), Throws.Exception.TypeOf<FormatException>());
}
The test fails, giving this error. Obviously I'm trying to test for this exception and I think I'm missing something in my syntax.
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)
based on the documentation at Throws Constraint (NUnit 2.5)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
基本上你需要将委托传递给
Assert.That
,就像链接状态中的文档一样(请注意,我在这里使用了 lambda 表达式,但它应该是相同的) 。Try this instead:
Basically you need to pass a delegate to
Assert.That
, just like the documentation in your link states (note that I've used a lambda expression here, but it should be the same).您使用什么测试运行器?并非所有这些都可以在异常断言下正常工作。
使用
[ExpectedException (typeof(FormatException))]
甚至Assert.Throws可能会有更好的运气。 (() => Int32.Parse("abc"));
What test runner are you using? Not all of them work correctly with the exception assertions.
You may have better luck using
[ExpectedException (typeof(FormatException))]
or evenAssert.Throws<FormatException> (() => Int32.Parse("abc"));