Search code examples
javajunithamcrest

How do I compare doubles using JUnit and Hamcrest?


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

Solution

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

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