Search code examples
assertj

assertThat returns() BigDecimal usingComparatorForType


I like to use asserThat().returns() combination to test the content of my objects. Unfortunately it does not work out of the box with BigDecimal because the equals method requires identical scale, which is not always the case. Instead the recommended way to assert BigDecimal is to use the .compare() method. Consequently I tried to specify a comparator for BigDecimal type, but it is not taken into account as the following test fails:

    @Test
    void test() {
        assertThat(new BigDecimal("10.00"))
                .usingComparatorForType(BigDecimalComparator.BIG_DECIMAL_COMPARATOR, BigDecimal.class)
                .returns(BigDecimal.TEN, BigDecimal::abs);
    }

I there a way to make the above test succeed, or is the only solution to use isEqualByComparingTo() which unfortunately breaks the nice chain of .returns()

assertThat(frodo)
    .returns("Frodo", from(TolkienCharacter::getName))
    .returns(HOBBIT, from(TolkienCharacter::getRace));

assertThat(frodo.size()).isEqualByComparingTo(new BigDecimal("1.2300"))

Solution

  • Since version 3.24.1, returns and doesNotReturn honor comparators configured via usingComparatorForType, so the original test should succeed:

    @Test
    void test() {
        assertThat(new BigDecimal("10.00"))
                .usingComparatorForType(BigDecimalComparator.BIG_DECIMAL_COMPARATOR, BigDecimal.class)
                .returns(BigDecimal.TEN, BigDecimal::abs);
    }