1. Introduction
1.绪论
In this tutorial, we’ll explore the differences between a failure and an error in JUnit tests.
在本教程中,我们将探讨JUnit测试中失败和错误之间的区别。
In short, failures are unfulfilled assertions while errors are due to abnormal test execution.
简而言之,失败是未完成的断言,而错误是由于异常的测试执行。
2. Sample Code
2.样品代码
Let’s consider a very simplistic example, namely a calculator class that has one method to divide two double values:
让我们考虑一个非常简单的例子,即一个计算器类,它有一个方法来除以两个double值。
public static double divideNumbers(double dividend, double divisor) {
if (divisor == 0) {
throw new ArithmeticException("Division by zero!");
}
return dividend / divisor;
}
Note that Java doesn’t actually throw an ArithmeticException on its own for double division – it returns Infinity or NaN.
请注意,Java实际上并没有为double除法抛出ArithmeticException,它返回Infinity或NaN。
3. Example Failure
3.失败的例子
When writing unit tests with JUnit, there will likely be situations when tests fail. One possibility is that our code does not meet its test criteria. That means one or more test cases fail due to assertions not being fulfilled.
在用JUnit编写单元测试时,很可能会出现测试失败的情况。一种可能性是,我们的代码不符合其测试标准。这意味着一个或多个测试案例由于断言未得到满足而失败。
In the following example, the assertion will fail, because the result of the division is 2 and not 15. Our assertion and the actual result simply don’t match:
在下面的例子中,断言将失败,因为除法的结果是2而不是15。我们的断言和实际结果根本不匹配。
@Test
void whenDivideNumbers_thenExpectWrongResult() {
double result = SimpleCalculator.divideNumbers(6, 3);
assertEquals(15, result);
}
4. Example Error
4.错误示例
Another possibility is that we have an unexpected situation during test execution, most likely due to an exception; for example, accessing a null reference will raise a RuntimeException.
另一种可能是,我们在测试执行过程中出现了意外情况,很可能是由于异常;例如,访问一个null引用会引发RuntimeException。
Let’s see an example, where the test will abort with an error because we’re attempting to divide by zero which we explicitly guard against by throwing an exception in our calculator code:
让我们看一个例子,测试会因错误而中止,因为我们试图除以0,而我们在计算器代码中明确地抛出了一个异常,以防止这种情况。
@Test
void whenDivideByZero_thenThrowsException(){
SimpleCalculator.divideNumbers(10, 0);
}
Now, we could fix this test by simply including the exception as one of our assertions.
现在,我们可以通过简单地将异常作为我们的assertions之一来修复这个测试。
@Test
void whenDivideByZero_thenAssertException(){
assertThrows(ArithmeticException.class, () -> SimpleCalculator.divideNumbers(10, 0));
}
Then, if the exception is thrown, the test passes, but if not then that would be another failure.
然后,如果抛出了异常,测试就通过了,但如果没有,那就是另一个失败。
5. Conclusion
5.总结
Both failure and error in JUnit tests indicate an undesired situation, but their semantics are different. Failures notify of an invalid test result, errors indicate an unexpected test execution.
JUnit测试中的失败和错误都表示不希望出现的情况,但它们的语义是不同的。失败通知一个无效的测试结果,错误表示一个意外的测试执行。
Also, please check out the example code at GitHub.
此外,请在GitHub查看示例代码。