gpt4 book ai didi

c# - NUnit 2016 抛出.TypeOf

转载 作者:太空狗 更新时间:2023-10-30 00:48:43 25 4
gpt4 key购买 nike

为什么这段代码抛出异常而不是通过测试?

public static int ThrowsSomething(string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name), "can't be null because that's silly");
return -1;
}

[Test]
public void WindowTest()
{
Assert.That(ThrowsSomething("dave"), Is.EqualTo(-1));
Assert.That(ThrowsSomething(null), Throws.TypeOf<ArgumentNullException>());
}

单元测试 session 窗口显示如下:

WindowTest [0:00.066] Failed: System.ArgumentNullException : can't be null because that's silly

带有 ReSharper Ultimate 2016.3 和 NUnit 3.6.1 的 Visual Studio 2015

最佳答案

测试失败,因为抛出的异常未被捕获并阻止测试完成。

使用 Assert.Throws<>断言抛出的异常

[Test]
public void WindowTest() {
Assert.That(ThrowsSomething("dave"), Is.EqualTo(-1));
Assert.Throws<ArgumentNullException>(() => ThrowsSomething(null));
}

或使用委托(delegate),以便异常可以被断言捕获和处理。

Assert.That(() => ThrowsSomething(null), Throws.Exception.TypeOf<ArgumentNullException>());

关于c# - NUnit 2016 抛出.TypeOf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43915632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com