20

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)); 
Tim B
  • 40,716
  • 16
  • 83
  • 128

4 Answers4

35

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

assertThat(result, closeTo(0.5, 0.1));
nickb
  • 59,313
  • 13
  • 108
  • 143
  • 7
    The full static import for those that are searching for it is: import static org.hamcrest.Matchers.closeTo; – Necrototem Oct 07 '16 at 11:02
6

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;
James Mudd
  • 1,816
  • 1
  • 20
  • 25
1

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.

Tim B
  • 40,716
  • 16
  • 83
  • 128
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.

Garret Wilson
  • 18,219
  • 30
  • 144
  • 272