c# - NUnit的TestCustomException不关心异常类型

标签 c# .net exception nunit

如果我想测试一个方法是否抛出特定类型的异常,NUnit 的 ExpectedException 属性并不关心实际类型;如果我在方法调用之前抛出通用异常,则测试通过:

    [Test, ExpectedException(typeof(TestCustomException))]
    public void FirstOnEmptyEnumerable()
    {
        throw new Exception(); // with this, the test should fail, but it doesn't
        this.emptyEnumerable.First(new TestCustomException());
    }

如果我想检查测试是否抛出确切的异常类型,我必须手动执行以下操作:

    [Test]
    public void FirstOnEmptyEnumerable()
    {
        try
        {
            throw new Exception();  // now the test fails correctly.
            this.emptyEnumerable.First(new TestCustomException());
        }
        catch (TestCustomException)
        {
            return;
        }

        Assert.Fail("Exception not thrown.");
    }

我错过了什么吗?

最佳答案

我从未使用过 ExpectedException,所以我对此没有任何经验可分享。一个选项是断言它直接在测试中抛出。像这样的事情:

[Test]
public void FirstOnEmptyEnumerable()
{
    Assert.Throws<TestCustomException>(() => this.emptyEnumerable.First(new TestCustomException()));
}

我发现这种方法更具可读性,因为您可以在预期发生的地方准确地测试异常,而不是说“在该函数内部的某个地方,我除了抛出异常”。

关于c# - NUnit的TestCustomException不关心异常类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3957151/

相关文章:

c# - Visual Studio 2017 工作室显示错误 'This application is in break mode' 并引发未处理的异常

c# - 获取 DayOfWeek 值的本地化字符串

c# - 统一容器 : Register two singletones which implement two interfaces one of which is common

python - 从回溯中获取最后一个函数的参数?

c# - 这个 "listMerging"代码可以改进吗?

c# - .NET 中最精确的计时器是什么?

c# - 如何使用 C# .Net 将屏幕捕获为视频?

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

java - 在orElseThrow中执行多行

c# - 在windows服务项目中注册autofac