Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# nUnit Assert.That(方法,Throws.Exception)不捕获异常_C#_.net_Nunit_Exception - Fatal编程技术网

C# nUnit Assert.That(方法,Throws.Exception)不捕获异常

C# nUnit Assert.That(方法,Throws.Exception)不捕获异常,c#,.net,nunit,exception,C#,.net,Nunit,Exception,有人能告诉我为什么这个检查异常的单元测试失败了吗?显然,我真正的测试是检查其他代码,但我使用Int32.Parse来显示问题 [Test] public void MyTest() { Assert.That(Int32.Parse("abc"), Throws.Exception.TypeOf<FormatException>()); } 根据上的文档,您使用的是什么测试运行程序?并不是所有的异常断言都能正常工作 使用[ExpectedException(typeof(F

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

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

根据

上的文档,您使用的是什么测试运行程序?并不是所有的异常断言都能正常工作

使用
[ExpectedException(typeof(FormatException))]
甚至
Assert.Throws(()=>Int32.Parse(“abc”))可能会更幸运

请尝试以下方法:

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

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

啊,我必须在匿名委托中进行。。。我现在在文档中看到,它不是非常清楚。谢谢如果有人发现他们的匿名函数返回void,您需要执行如下操作:
Assert.that(新操作(()=>VoidReturningMethod(“abc”)),Throws.Exception.TypeOf()
感谢@Martineal在正确的道路上帮助了我,但对我来说,它抱怨它必须是一个TestDelegate,所以我必须这样做:
新的TestDelegate(()=>AddBlockingTaskToBox())
orI正在使用TDD.net和nUnit gui。你的修正成功了,但我想使用流畅的语法。但是我给了你一个帮助的分数!我知道这是一个古老的答案,当时是正确的。但对于现在和将来的引用,
ExpectedException
属性在NUnit 3.0上不受欢迎:您也可以这样做:
Assert.Throws(()=>Int32.Parse(“abc”)我试图坚持断言。这种风格适合这个项目。我不再像以前那样依恋它了。
Assert.That(() => Int32.Parse("abc"), Throws.Exception.TypeOf<FormatException>());