I am testing one of my methods, double getSqrt(double s), and having the following JUnit test code:
@Test
public void testGetSqrt() {
System.out.println("getSqrt");
double s = 16.0;
Calculator instance = new Calculator();
double expResult = 4.0;
double result = 4.000000000052429; // was "instance.getSqrt(s);" here
// now hardcode for test purpose
System.out.println(System.getProperty("java.class.path"));
assertEquals(expResult, result, 0.0);
}
It failed every time, no matter how I changed the tolerance "0.0", "0.1", "0.00", "0.01", "0.001".... The report is the following:
AssertionFailedError: expected:<4.0>; but was:<4.000000000052429>
What I am using is JUnit 4.12 and Hamcrest 1.3.
And my imports:
import org.junit.Test;
import static org.junit.Assert.*;
Did I use the tolerance wrong?
Output on the console:
compile-test-single:
Testsuite: descriptivestatisticsapplication.processing.CalculatorTest
getSqrt
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.079 sec
------------- Standard Output ---------------
getSqrt
C:\Java\jdk1.8.0_111\jre\lib\javaws.jar;C:\Java\jdk1.8.0_111\jre\lib\deploy.jar;C:\Java\jdk1.8.0_111\jre\lib\plugin.jar;C:\Users\Z\Documents\NetBeansProjects\DescriptiveStatisticsApplication\build\classes;C:\Program Files\NetBeans 8.2\platform\modules\ext\junit-4.12.jar;C:\Program Files\NetBeans 8.2\platform\modules\ext\hamcrest-core-1.3.jar;C:\Users\Z\Documents\NetBeansProjects\DescriptiveStatisticsApplication\build\test\classes;C:\Program Files\NetBeans 8.2\extide\ant\lib\ant-launcher.jar;C:\Program Files\NetBeans 8.2\extide\ant\lib\ant.jar;C:\Program Files\NetBeans 8.2\extide\ant\lib\ant-junit.jar;C:\Program Files\NetBeans 8.2\extide\ant\lib\ant-junit4.jar
------------- ---------------- ---------------
Update on 5/27:
After doing some tests from the suggestions in the comments, this unit test can now pass successfully. I think this question can be closed.
What I worry about is I didn't find out any reason why it failed and why now it succeed! Same code, same logic! The only thing I have done is like commenting out some non-important lines and then adding them back, changing some declaration statements sequence and then changing them back. The same code has different behaviors. I haven't changed anything in the building and running env and libs. This doesn't make any sense. The result from a piece of code should be reproducible.