NUnit的Assert.That(方法,Throws.Exception)没有捕获异常 [英] nUnit Assert.That(method,Throws.Exception) not catching exceptions
问题描述
为什么这个单元测试,检查异常失败,有人能告诉我吗?显然,我的真正的考验是检查等code,但我使用Int32.Parse显示的问题。
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)
推荐答案
试试这个来代替:
Assert.That(() => Int32.Parse("abc"), Throws.Exception.TypeOf<FormatException>());
基本上,你需要一个委托传递给 Assert.That
,就像在你的链路状态(文档请注意,我用一个lambda EX pression在这里,但它应是相同的)。
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).
这篇关于NUnit的Assert.That(方法,Throws.Exception)没有捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!