Jas*_*ore 42 .net c# nunit exception
有人能告诉我为什么检查异常的单元测试失败了吗?显然我真正的测试是检查其他代码,但我正在使用Int32.Parse来显示问题.
[Test]
public void MyTest()
{
Assert.That(Int32.Parse("abc"), Throws.Exception.TypeOf<FormatException>());
}
Run Code Online (Sandbox Code Playgroud)
测试失败,给出了这个错误.显然我正在尝试测试这个异常,我想我的语法中缺少一些东西.
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)
Run Code Online (Sandbox Code Playgroud)
Kla*_*sen 65
试试这个:
Assert.That(() => Int32.Parse("abc"), Throws.Exception.TypeOf<FormatException>());
Run Code Online (Sandbox Code Playgroud)
基本上你需要传递一个委托Assert.That,就像链接状态中的文档一样(注意我在这里使用了lambda表达式,但它应该是相同的).
你在用什么测试跑步者?并非所有这些都与异常断言一起正常工作.
你可能有更好的运气使用[ExpectedException (typeof(FormatException))]甚至Assert.Throws<FormatException> (() => Int32.Parse("abc"));