Using Hamcrest `closeTo` with a float

2 weeks ago 11
ARTICLE AD BOX

I have a unit test where I am trying to do

assertThat(foo, hasProperty("bar", hasProperty("qua", is(closeTo(17.0f, 1e-5)))));

That is, I have foo and want to verify that foo.getBar().getQuz() is approximately 17. closeTo is declared to take a double or a BigDecimal

When I run the test, it appears to fail, because getQuz returns a float and (at least to Hamcrest) 17.0f and 17.0 (the double value) are different types and cannot be closeTo.

is a numeric value within <1.0E-5> of <17.0>) property "quz" was a java.lang.Float (<17.0F>)]

Is there a way to get this to work?

I know that I could write assertThat(foo.getBar().getQuz(), is(closeTo(17.0, 1e-5)) and then cast to get it to work, but the actually query is more complicated:

assertThat(..., hasItem(hasProperty(..., allOff(hasProperty(...), hasProperty(...), hasProperty(...)))))

so I am asserting that the list has a single element where a nested property has three different properties with specified values. Writing that out is going to be a complicated piece of code, and probably not give me as nice of an error message when the test fails.

Read Entire Article