How do I compare doubles using JUnit and Hamcrest?

Tim B picture Tim B · Dec 18, 2015 · Viewed 10.8k times · Source

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)); 

Answer

nickb picture nickb · Dec 18, 2015

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

assertThat(result, closeTo(0.5, 0.1));