Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit assertions : make the assertion between floats

Tags:

java

junit

junit4

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 ?

like image 842
lola Avatar asked Sep 26 '11 11:09

lola


People also ask

What is float Delta in assertEquals?

public static void assertEquals(String message, float expected, float actual, float delta) Asserts that two floats are equal to within a positive delta. If they are not, an AssertionError is thrown with the given message. If the expected value is infinity then the delta value is ignored.

What do assertions do in JUnit?

Assertions are utility methods to support asserting conditions in tests; these methods are accessible through the Assert class, in JUnit 4, and the Assertions one, in JUnit 5.

How do you group assertions together in JUnit?

Grouped Assertions With Heading As Parameter Here is an example where assertEquals () and assertIterableEquals () are grouped together using the method assertAll (). It consists of the heading parameter with the value “GroupedAssertionHeading”. Result : As both asserts are passed, the final result passes.

How do you assert two objects are equal in JUnit?

assertEquals() calls equals() on your objects, and there is no way around that. What you can do is to implement something like public boolean like(MyClass b) in your class, in which you would compare whatever you want. Then, you could check the result using assertTrue(a. like(b)) .


1 Answers

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 
like image 59
oers Avatar answered Oct 08 '22 01:10

oers