如果我想测试一个方法是否抛出特定类型的异常,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/