I am running assertions like so:
assertThat(obj.getTotal()).isEqualTo(BigDecimal.valueOf(4))
I am getting
Expecting: <4.00> to be equal to: <4>
so then I tried
assertThat(obj.getTotal()).isEqualTo(BigDecimal.valueOf(4.00))
Expecting: <4.00> to be equal to: <4.0>
I found a workaround in which I would set the scale of expected value 4
to 4.00
, but it seems quite irritating that I have to do so for all BigDecimal variables in my tests. Is there a better way from AssertJ that I am unaware of?
You can use isEqualByComparingTo
or usingComparator
that use BigDecimal.compareTo
which compares the actual numeric value. The equals
method which is the default assertj uses does the following according to JavaDoc:
Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).
So you can do:
assertThat(obj.getTotal())
.usingComparator(BigDecimal::compareTo)
.isEqualTo(BigDecimal.valueOf(4.00));
or simply:
assertThat(obj.getTotal())
.isEqualByComparingTo(BigDecimal.valueOf(4.00));
To use with Iterable
and extracting
assertions:
assertThat(asList(new Trade("1", new BigDecimal("5.200")), new Trade("2", new BigDecimal("4.00"))))
.extracting(Trade::getId, Trade::getAmount)
.usingComparatorForType(BigDecimal::compareTo, BigDecimal.class)
.usingRecursiveFieldByFieldElementComparator()
.containsExactlyInAnyOrder(tuple("1", new BigDecimal("5.2")), tuple("2", new BigDecimal("4")));