Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit assertEquals(double expected, double actual, double epsilon) [duplicate]

Tags:

java

junit

Possible Duplicate:
JUnit: assertEquals for double values

Apparently the assertEquals(double expected, double actual) has been deprecated.

The javadocs for JUnit are surprisingly lacking, considerings its wide use. Can you show me how to use the new assertEquals(double expected, double actual, double epsilon)?

like image 835
LuxuryMode Avatar asked May 09 '11 16:05

LuxuryMode


People also ask

How do you compare double values in JUnit?

In fact, JUnit provides a set of comparing methods for common objects, collections, and primitive types, including dedicated methods to check double values equality: double epsilon = 0.000001d; assertEquals(d1, d2, epsilon);

What is Epsilon in assertEquals?

Epsilon is the value that the 2 numbers can be off by. So it will assert to true as long as Math.abs(expected - actual) <= epsilon.

Why is assertEquals double deprecated?

assertEquals(double, double) is deprecated because the 2 doubles may be the same but if they are calculated values, the processor may make them slightly different values.

What is expected and actual in assertEquals?

assertEquals. Asserts that two object arrays are equal. If they are not, an AssertionError is thrown. If expected and actual are null , they are considered equal.


1 Answers

Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.

If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like

double myPi = 22.0d / 7.0d; //Don't use this in real life! assertEquals(3.14159, myPi, 0.001); 

(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)

like image 127
rajah9 Avatar answered Sep 26 '22 00:09

rajah9