繁体   English   中英

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

[英]nUnit Assert.That(method,Throws.Exception) not catching exceptions

有人能告诉我为什么检查异常的单元测试失败了吗? 显然我真正的测试是检查其他代码,但我正在使用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.That(() => Int32.Parse("abc"), Throws.Exception.TypeOf<FormatException>());

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

你在用什么测试跑步者? 并非所有这些都与异常断言一起正常工作。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM