Dragon - 11 months ago 48

Java Question

assertEquals for doubles is deprecated. I found that the form with Epsilon should be used. It is because of impossible 100% strictness of doubles. But anyway I need to compare two doubles (expected and actual result), but I don't know how to do it.

At the moment my test looks like:

`@Test`

public void testCalcPossibleDistancePercentageCount() {

int percentage = 100;

assertEquals("Wrong max possible value for %" + percentage, 110.42, processor.calcPossibleValue(percentage));

percentage = 75;

/*corresponding assertions*/

}

Here are 3 double values I receive and which I want to check with JUnit: 110.42, 2760.5 and 10931.58.

How should JUnit test look like with assertions for them? I receive them as a result of calculation in a method:

`processor.calcPossibleValue(allowed_percentage){return /*Some weird formulae here*/;}`

Answer Source

You need to add a fourth parameter to the `assertEquals`

call: the threshold within which two doubles should be considered "equal". Your call should look like this:

```
assertEquals("Wrong max possible value for %" + percentage, 110.42,
processor.calcPossibleValue(percentage), 0.01);
```

The above call would indicate that if the value returned by `processor.calcPossibleValue(percentage)`

is within ± 0.01 of `110.42`

, then the two values are considered equal. You can change this value to make it as small as is necessary for your application.

See the JUnit documentation for more information.