111

Possible Duplicate:
JUnit: assertEquals for double values

Apparently the assertEquals(double expected, double actual) has been deprecated.

The javadocs for JUnit are surprisingly lacking, considerings its wide use. Can you show me how to use the new assertEquals(double expected, double actual, double epsilon)?

Community
  • 1
  • 1
LuxuryMode
  • 33,401
  • 34
  • 117
  • 188

1 Answers1

183

Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.

If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like

double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);

(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)

rajah9
  • 11,645
  • 5
  • 44
  • 57
  • I have a special `max` function where `max(NaN,3.0)` equals `3.0` in contrary to the original behavior which tells `NaN`. In my test cases `assertEquals(double,double)` is the desired thing and I don't get why it got deprecated. Sometimes you can expect punctual results even when you use `float` or `double`. – Notinlist Oct 20 '15 at 09:23
  • The delta value is indeed the "error" or "uncertainty" allowed in the comparison. Other popular test frameworks such as TestNG and MsTest also have similar AssertEqual methods. TestNG has assertEquals(double actual, double expected, double delta) NUnit has Assert.AreEqual( double expected, double actual, double tolerance ) MsTest has Assert.AreEqual Method (Double, Double, Double) – Ravishankar S May 21 '18 at 01:01