[英]TestNG classes expecting Exception.class
I have inherited some code from another team which uses 我已经从另一个团队继承了一些代码,
@Test (expectedExceptions = {Exception.class})
everywhere when the code might be throwing a more specific exception. 当代码可能会抛出更具体的异常时,到处都是。
My understanding is that this is wrong because we are not expecting the right type of exception. 我的理解是,这是错误的,因为我们没有期望正确的异常类型。 But the current owners are saying that they have seen no issue because of this.
但是目前的业主说,因此他们没有发现任何问题。
Is my understanding correct? 我的理解正确吗?
This is poor design, since it could be masking errors other than the one being tested for. 这是糟糕的设计,因为它可能掩盖了除了要测试的错误以外的其他错误。 As an example, suppose your code should throw a
SecurityException
on some operation but instead is throwing a NullPointerException
because of a naive dereference. 例如,假设您的代码应该在某些操作上引发
SecurityException
,但是由于天真的取消引用而引发了NullPointerException
。 Your test would pass when it should fail. 您的测试将在失败时通过。
You should always make your matchers as specific as possible, and in this case, that means the most specific exception class that applies. 您应该始终使匹配器尽可能具体,在这种情况下,这意味着最适用的异常类。
Exception is Parent class of all types of exception in java, so basically your test will pass if code throws any checked or unchecked exception. 异常是Java中所有类型的异常的父类,因此,基本上,如果代码抛出任何已检查或未检查的异常,则测试将通过。 But its better to write unit test that will expect a particular type of exception which your code can throw.
但是最好编写单元测试,以期望代码可以抛出特定类型的异常。 For eg let say your have a method to validateParam
例如,假设您有一个validateParam方法
public void validateParam(String param) throws SomeCustomValidationException {
//suppose param is null , now this code will throw NullPointerException
if (param.length() > 2) {throw new SomeCustomValidationException();}
}
and you call it like this 你这样称呼它
public void businessLogic(String param) {
try {validateParam(param);}
catch(SomeCustomValidationException e){//show error dialog to the user}
}
So although your unit test will pass but your business logic will not work as you expected 因此,尽管您的单元测试将通过,但是您的业务逻辑将无法按预期工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.