How do I compare doubles using JUnit and Hamcrest?
Asked Answered
D

4

22

I'm writing a unit test using JUnit and Hamcrest. I have been comparing double values using:

assertThat(result, is(0.5));

However, I'm now needing to compare calculated values and I don't want to have to compare against the full double value. Instead, I want to compare for closeness.

I've discovered a class called IsCloseTo but I'm not sure how to use it in an assertThat and I can't find any examples online.

What's the correct syntax to do something like the following?

// I can't do this as I need to know what methods/classes whatever I should be using
// isCloseTo doesn't exist.
assertThat(result, isCloseTo(0.5, 0.1)); 
Disparate answered 18/12, 2015 at 16:3 Comment(0)
A
36

You should be able to call Matchers.closeTo(double, double). With a static import, it looks like:

assertThat(result, closeTo(0.5, 0.1));
Allocate answered 18/12, 2015 at 16:10 Comment(1)
The full static import for those that are searching for it is: import static org.hamcrest.Matchers.closeTo;Cahra
P
8

You can make this read better if you use

assertThat(actual, is(closeTo(expected, delta)));

with

import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.is;
Proprietor answered 20/6, 2018 at 15:31 Comment(2)
closeTo doesn't need is wrapperCheetah
That's correct it doesn't need it. It's to make the code more readable.Proprietor
D
2

Just worked it out, is actually returns an Is object, so all I needed to do was:

assertThat(result, new IsCloseTo(0.5, 0.1)); 

The answer from nickb is better though.

Disparate answered 18/12, 2015 at 16:5 Comment(0)
C
0

A good approach would be to use the closeTo() matcher (as others have indicated), using Math.ulp() to produce the error value. See What should be the epsilon value when performing double value equal comparison for more discussion. I've opened Hamcrest Issue #402 requesting that this capability be added to Hamcrest as a simpler closeTo() method that automatically calculates the error value.

Coagulum answered 1/8, 2023 at 14:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.