JUnit Assert with BigDecimal

后端 未结 9 2007
遇见更好的自我
遇见更好的自我 2021-02-02 05:47

I want to use assert between 2 two decimal, I use this:

BigDecimal bd1 = new BigDecimal (1000);
BigDecimal bd2 = new BigDecimal (1000);
org.junit.Assert.assertSa         


        
9条回答
  •  春和景丽
    2021-02-02 06:29

    Comparing BigDecimal with compareTo() works (as in: it ignore the scale and compare the actual number) but when unit testing it's useful to know what's the actual number, specially when the test fail.

    An option I've used in this case is stripTrailingZeros() on both BigDecimal:

    assertEquals(new BigDecimal("150").stripTrailingZeros(),
                        otherBigDecimal.stripTrailingZeros());
    

    What this function does is remove zeroes without changing the number, so "150" is converted in "1.5E+2": this way it doesn't matter if you have 150, 150.00 or other form in otherBigDecimal because they get normalized into the same form.

    The only difference is a null in otherBigDecimal would give a NullPointerException instead of an assertion error.

提交回复
热议问题