JUnit assertions : make the assertion between floats

JavaJunitJunit4

Java Problem Overview


I need to compare two values : one a string and the other is float so I convert the string to float then try to call assertEquals(val1,val2) but this is not authorized , I guess that the assertEquals doesn't accept float as arguments.

What is the solution for me in this case ?

Java Solutions


Solution 1 - Java

You have to provide a delta to the assertion for Floats:

Assert.assertEquals(expected, actual, delta)

While delta is the maximum difference (delta) between expected and actual for which both numbers are still considered equal.

Assert.assertEquals(0.0012f, 0.0014f, 0.0002); // true
Assert.assertEquals(0.0012f, 0.0014f, 0.0001); //false

Solution 2 - Java

A delta-value of 0.0f also works, so for old fashioned "==" compares (use with care!), you can write

Assert.assertEquals(expected, actual, 0.0f);

instead of

Assert.assertEquals(expected, actual); // Deprecated
Assert.assertTrue(expected == actual); // Not JUnit

I like the way JUnit ensures that you really thought about the "delta" which should only be 0.0f in really trivial cases.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlolaView Question on Stackoverflow
Solution 1 - JavaoersView Answer on Stackoverflow
Solution 2 - JavaRedXIIIView Answer on Stackoverflow