Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/294.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# 哪里是通用DoesNotThrow<;T>;与投掷类似的方法<;T>;方法?_C#_Nunit - Fatal编程技术网

C# 哪里是通用DoesNotThrow<;T>;与投掷类似的方法<;T>;方法?

C# 哪里是通用DoesNotThrow<;T>;与投掷类似的方法<;T>;方法?,c#,nunit,C#,Nunit,列表列出了几种形式。撇开重载不谈,以下表单可用: Assert.Throws(/* params here, incl. delegate w/ code */) Assert.Throws<T>(/* params here, incl. delegate w/ code */) Assert.DoesNotThrow(/* params here, incl. delegate w/ code */) Assert.Throws(/*参数在这里,包括带/code*/的委托) A

列表列出了几种形式。撇开重载不谈,以下表单可用:

Assert.Throws(/* params here, incl. delegate w/ code */)
Assert.Throws<T>(/* params here, incl. delegate w/ code */)
Assert.DoesNotThrow(/* params here, incl. delegate w/ code */)
Assert.Throws(/*参数在这里,包括带/code*/的委托)
Assert.Throws(/*此处为参数,包括带代码的委托*/)
Assert.DoesNotThrow(/*此处为参数,包括带代码的委托*/)
我这里少了一个,这也是我所期望的:

Assert.DoesNotThrow<T>(/* params here, incl. delegate w/ code */)
Assert.DoesNotThrow(/*此处为参数,包括带代码的委托*/)
目前我只使用可用的
DoesNotThrow
版本,并祈祷它永远不会隐藏表明问题的异常类型。这实在令人不满意

我真的想在测试中相关的异常(例如,
Assert.DoesNotThrow
)和不相关的异常(例如,
NullReferenceException
)之间建立一个区别。这不是什么大问题,因为非泛型断言不会影响测试何时为红色/绿色,但会影响它报告为红色的方式


在我跑去创建自己的断言扩展来处理这个问题之前,我想问:我在这里遗漏了什么吗?我想要的表格是否有原因不可用?其他NUnit比特能实现这一点吗?

评论和缺乏答案表明NUnit中根本没有这种方法

正如注释中所建议的,您可以使用
DoesNotThrow
非泛型方法,只需忽略以下事实:其他类型的异常将显示与断言失败相同类型的输出

评论中的另一个建议是编写自己的helper方法,如果有人在意,这里有一个可能的版本:

public static void AssertDoesNotThrow<T>(NUnit.Framework.TestDelegate testDelegate) where T : Exception
{
    try
    {
        testDelegate.Invoke();
    }
    catch (T exception)
    {
        Assert.Fail("Expected: not an <{0}> exception or derived type.\nBut was: <{1}>",
                    typeof (T).FullName, 
                    exception.GetType().FullName);
    }
}
publicstaticvoidassertdoesnotthrow(NUnit.Framework.TestDelegate TestDelegate),其中T:Exception
{
尝试
{
testDelegate.Invoke();
}
捕获(T异常)
{
Assert.Fail(“预期:不是异常或派生类型。\n但为:”,
typeof(T).全名,
异常。GetType().FullName);
}
}
对于违反断言的测试委托,您会得到一个不错的“失败”和以下类型的输出:

应为:不是异常或派生类型。

But was:

对于意外错误,异常本身的测试失败


至于我自己,我想我会接受这样一个事实,即这在vanilla NUnit中并不存在,然后继续使用非泛型版本。

有几乎无限多的异常,测试方法不会抛出。你从哪里开始?只需编写一个小的helper方法,它使用try/catch来吞咽除要测试的异常之外的所有异常。在测试委托中,您是否尝试过尝试/捕获以处理您认为“OK”的异常,并在未处理的任何事情上使测试失败?谢谢您的支持!“您从哪里开始?”,在测试涉及的异常中,我的场景中是一个SqlException。如果抛出异常,我希望看到一个失败的断言,如果抛出任何其他异常,我希望测试“正常”中断。这将在我的测试结果中提供更清晰的反馈(即,我不想吞并/隐藏其他异常,我只希望它们在测试结果中看起来不同)。