Search code examples
javatestngassertions

TestNG AssertEquals double - good number to put for a double?


Using TestNG's Assert.assertEquals(double expected, double actual, double delta), what would be a good number to use for a delta using the following numbers (assertion failed because there is no delta)

AssertionError: expected [121.97] but found [121.96999999999998]

I tried using 1, .01, and .001, but all three passed. I want to keep the allowance for success to be very small (in other words, if the "actual numbers" (from my perspective anyways) were 121.97 and 121.96 I want the test to to fail. Thanks!


Solution

  • If you want your test to fail for 121.97 and 121.96... try using delta that is smaller than
    |121.97 - 121.96| = 0.01.
    How about:

    final double DELTA = 0.001;
    assertEquals(121.97, 121.96, DELTA);
    

    Output:

    java.lang.AssertionError: expected [121.96] but found [121.97]
    Expected :121.96
    Actual   :121.97
    

    In general case... if you want your assertion to fail for a and b,
    use delta that is smaller than |a - b|.