JUnit and float values

7 views
Skip to first unread message

Mat Gessel

unread,
Jun 28, 2006, 3:47:17 AM6/28/06
to Google Web Toolkit
This assertion

> assertEquals(0.0f, 0.0f, 0.0f);

Results in the following failure in hosted and web modes:

> junit.framework.AssertionFailedError: expected=0.0 actual=0.0 delta=0.0

While this assertion passes:

> assertEquals(0.0f, 0.1f, 0.0f);

So, this JUnit method seems to be broken. Also, when stepping into this
method in the debugger (hosted mode) the line numbers are all wrong. It
works fine for regular ol' TestCase (not GWTTestCase). I'm using JUnit
version 3.8.1 jar and source.

I have no current need to allow for precision so I'm using the
following workaround to verify values in my tests:

> assertTrue(0.0f == 0.0f);

-= Mat

Paul Strack

unread,
Jun 28, 2006, 7:42:30 PM6/28/06
to Google Web Toolkit
The whole poinit of the third parameter in the assert method for floats
and reals is that it is unlikely you will get exact equality with
floating point numbers. Try something like this:

assertEquals(0.0f, 0.0f, 0.0001f)

The means "equal within a 0.0001 margin of error."

Mat Gessel

unread,
Jun 28, 2006, 9:21:27 PM6/28/06
to Google Web Toolkit
After some shpeee-lunking in gwt-user.jar I think I found the source
for runtime:
com\google\gwt\junit\translatable\junit\framework\Assert.java

static public void assertEquals(String str, float obj1, float obj2,
float delta) {
if (obj1 - obj2 < delta || obj2 - obj1 < delta) {
return;
} else {
fail(str + " expected=" + obj1 + " actual=" + obj2 + " delta=" +
delta);
}
}

It should be something like this:

if (obj1 > obj2 && obj1 - obj2 < delta || obj2 - obj1 <= delta)
return;
else
fail();

The assertEquals(String, double, double, double) method is also
affected.

-= Mat

Reply all
Reply to author
Forward
0 new messages