JUnit assertions : make the assertion between floats
I need to compare two values : one a string and the other is float
so I convert the string to floa开发者_开发技巧t 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 ?
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
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.
精彩评论