nUnit Assert.That(方法,Throws.Exception)不捕获异常 [英] nUnit Assert.That(method,Throws.Exception) not catching exceptions

查看:192
本文介绍了nUnit Assert.That(方法,Throws.Exception)不捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

测试失败,导致此错误。显然,我试图测试这个异常,我想我在我的语法中缺少一些东西。

 错误1 TestCase' .MyTest'
失败:System.FormatException:输入字符串格式不正确。
在System.Number.StringToNumber(String str,NumberStyles options,NumberBuffer& number,NumberFormatInfo info,Boolean parseDecimal)
在System.Number.ParseInt32(String s,NumberStyles style,NumberFormatInfo info)
在System.Int32.Parse(String s)

根据抛出约束(NUnit 2.5)

解决方案

尝试这样做:

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

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


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)

解决方案

Try this instead:

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆