Jon
Jon

Reputation: 4055

Junit assertEquals on objects with double fields

I have two Lists of Objects. These objects reference other objects which in turn contain doubles. I want to use assertEquals to test that the two objects are the same. I have verified by hand that they are, but assertEquals is still returning false. I think the reason is because the doubles are not the same because of precision issues. I know that I can solve this problem by drilling down to the double fields and using assertEquals(d1, d2, delta), but that seems cumbersome. Is there anyway to provide a delta to assertEquals (or another method), such that it can use that delta whenever it encounters doubles to compare?

Upvotes: 1

Views: 656

Answers (1)

Joe
Joe

Reputation: 31087

Hamcrest matchers may make this a little easier. You can create a custom Matcher (or a FeatureMatcher - Is there a simple way to match a field using Hamcrest?), then compose it with a closeTo to test for doubles, and then use container matchers (How do I assert an Iterable contains elements with a certain property?) to check the list.

For example, to check for a list containing exactly one Thing, which has a getValue method returning approximately 10:

Matcher<Thing> thingWithExpectedDouble =
    Matchers.<Thing>hasProperty("value", Matchers.closeTo(10, 0.0001));
assertThat(listOfItems, Matchers.contains(thingWithExpectedDouble));

Upvotes: 0

Related Questions