I am confused regarding the delta/precision in assertEquals
.
I understand that 0.034
will give me the precision for my division code, as shown below:
public void testDivide() {
assertEquals(3.0, Arithmetic.divide(12.0, 4.0), 0.0);
assertEquals(3.3, Arithmetic.divide(10.0, 3.0), 0.034);
//fail("Not yet implemented");
}
However, I tried to change it to 0.03
, the test failed. On the other hand, when I change it to 0.04
, it succeeded, or even if I change it to 0.034444
and so forth, it will succeed.
May I know what does the number mean, and how do we use it?
The assert. equal() method tests if two values are equal, using the == operator. If the two values are not equal, an assertion failure is being caused, and the program is terminated.
Procedure assertEquals has two parameters, the expected-value and the computed-value, so a call looks like this: assertEquals(expected-value, computed-value);
assertEquals() methods checks that the two objects are equals or not. If they are not, an AssertionError without a message is thrown. Incase if both expected and actual values are null, then this method returns equal.
assertEquals() The assertEquals() method compares two objects for equality, using their equals() method.
You are using:
assertEquals
(double expected, double actual, double epsilon)
Since doubles may not be exactly equal in any language (precision issues), epsilon allows you to describe how close they have to be.
Epsilon is defined as the maximal deviation from the expected
result:
Math.abs(expected - actual) < epsilon
So in essence it allows you to deviate from the expected
outcome (3.0
or 3.3
in your cases) byArithmetic.divide(12.0, 4.0) - 3.0 = 3.0 - 3.0 = 0
andArithmetic.divide(10.0, 3.0) - 3.3 ≈ 3.3333333 -3.3 ≈ 0.3333333
respectively.
So in the first one as you see, there is actually no need for an epsilon since the expected
and actual
results are exactly the same.
In the second one you should allow some deviation as you see that the actual
result is approximately >
by 0.33333
than the expected
one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With