JUnit assertions : make the assertion between floats

我只是一个虾纸丫 提交于 2019-12-20 10:18:04

问题


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 ?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/7554281/junit-assertions-make-the-assertion-between-floats

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!