Home > Back-end >  JUnit testing: how to correctly set dynamic delta for assertEquals()?
JUnit testing: how to correctly set dynamic delta for assertEquals()?

Time:11-12

for an assignment I have to implement my own floats. They are working for many possible combinations of inputs i could think of, so I set out to make a JUnit test with random values. Now I encountered some trouble with dynamically setting the delta value in the method call assertEquals(String message, Double expected, Double actual, Double delta).

This is my test method:

@Test
public void testRandomMath() {

    DoubleStream doubleStream = ThreadLocalRandom.current().doubles(100);

    //limiting the doubles to be withing a workable range for my ownFloat class
    double[] doubles = doubleStream.map(d -> {
        if (ThreadLocalRandom.current().nextBoolean()) {
            return d * -1d;
        }
        else {
            return d;
        }
    }).map(d -> d * Math.pow(2, ThreadLocalRandom.current().nextInt(-8, 9))).toArray();

    OwnFloat[] ownFloats = new OwnFloat[doubles.length];

    for (int i = 0; i < doubles.length; i  ) {
        ownFloats[i] = new OwnFloat(doubles[i]);
    }

    for (int i = 0; i < doubles.length; i  ) {
        for (int j = 0; j < doubles.length; j  ) {
            assertEquals("Failed "   doubles[i]   "   "   doubles[j],doubles[i]   doubles[j], ownFloats[i].add(ownFloats[j]).toDouble(), Math.min(doubles[i], doubles[j]));
            assertEquals("Failed "   doubles[i]   " - "   doubles[j], doubles[i] - doubles[j], ownFloats[i].sub(ownFloats[j]).toDouble(), Math.min(doubles[i], doubles[j]));
        }
    }
}

And this is the test error:

java.lang.AssertionError: Failed -0.01393084463838419   -0.01393084463838419 
Expected :-0.02786168927676838
Actual   :-0.027861595153808594

What am I getting wrong about how the delta works? What could I use instead of the minimum of the inputs as delta value?

Kind regards, Lantanar

CodePudding user response:

After some testing I found out that delta has to be a positive value. Finally I settled for

Math.max(Math.abs(doubles[i]), Math.abs(doubles[j])) / 100

as delta.

CodePudding user response:

You should set the delta directly depending on your use case.

In your case delta = 1e-6 should be sufficient.

  • Related