如果我想测试一个方法是否抛出特定类型的异常,NUnit的ExpectedException属性并不关心实际类型;如果在方法调用之前抛出一个泛型Exception,则测试通过:
[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.");
}
我是不是错过了什么?