NUnit 的 TestCustomException 不关心异常类型
如果我想测试一个方法是否抛出特定类型的异常,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.");
}
我是否遗漏了某些内容?
If I want to test that a method throws an exception of a particular type, NUnit's ExpectedException attribute doesn't care about the actual type; if I throw a generic Exception before the method call, the test passes:
[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());
}
If I want to check that the test throws the exact exception type, I have to do something manual like this:
[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.");
}
Am I missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我从未使用过 ExpectedException,所以我对此没有任何经验可分享。一个选项是断言它直接在测试中抛出。像这样的事情:
我发现这种方法更具可读性,因为您在预期异常发生的地方测试异常,而不是说“在这个函数的某个地方,我除了抛出一个异常”。
I've never used ExpectedException, so I don't have any experience to share on this. An option is to Assert that it Throws directly inside the test. Something like this:
I find this approach more readable as you test for the exception exactly where you expect it to happen instead of saying "somewhere inside this function I except an exception to be thrown".
我总是测试异常的字符串表示形式,例如:
这似乎对我来说效果很好。
I always test for the string representation of the exception e.g.:
Which seems to work fine for me.
如果要使用 ExpectedException(string) 签名,最佳实践是使用 typeof(Exception).Name 和 typeof(Exception).Namespace
If you want to use the ExpectedException(string) signature, the best practice would be to use typeof(Exception).Name and typeof(Exception).Namespace