Darth.Vader
Darth.Vader

Reputation: 6271

Junit testing for hashMap with double values

I am using Junit to assert equality berween the expected and actual HashMaps I receive after calling a method. The code looks like this:

Assert.assertEquals(expectedKlassToScore, klassToScore);

Here expectedKlassToScore and klassToScore are of type Map<MyObject, Double>. Some of the values in the HashMap are upto 16 digits long after the decimals. I am assuming that depending on the machine that these tests run, the last few decimal places might be inaccurate - due to the nature of how fractions are implemented on the hardware.

How can I modify my assert statement to enable a Window of accuracy for letting the tests pass on different machines?

Upvotes: 2

Views: 10856

Answers (4)

Liviu Stirb
Liviu Stirb

Reputation: 6075

public static void assertEqualsMapEpsilon(Map<Object,Double> expected, Map<Object,Double> actual, double epsilon) {
    assertEquals(expected.size(), actual.size());
    for(Map.Entry<Object,Double> value:expected.entrySet()){
        Double actualValue = actual.get(value.getKey());
        assertNotNull(actualValue);
        assertEquals(value.getValue(), actualValue, epsilon);
    }
}

Upvotes: 3

rhobincu
rhobincu

Reputation: 926

As you can see here, Assert.assertEquals uses the equals() method to check if the objects are equal. I'd say the easiest way would be to create a class that implements Map<> and override the equals method.

Upvotes: 0

user207421
user207421

Reputation: 310980

Some of the values in the HashMap are upto 16 digits long after the decimals.

Wrong. None of the double values in the HashMap are up to 16 digits long after the decimals. Double-precision floating-point has a maximum of 15.9 significant decimal digits. Anything else is an illusion.

I am assuming that depending on the machine that these tests run, the last few decimal places might be inaccurate - due to the nature of how fractions are implemented on the hardware.

Wrong again. The formats and ranges of all primitive types in Java are hardware-independent.

How can I modify my assert statement to enable a Window of accuracy for letting the tests pass on different machines?

Test for equality within an epsilon value.

Upvotes: -2

Adam Arold
Adam Arold

Reputation: 30548

You should use BigDecimal for this. Doubles are always inaccurate.

Upvotes: 0

Related Questions