javajunitassertbigdecimal

JUnit Assert with BigDecimal


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.assertSame (bd1,bd2);

but the JUnit log shows:

expected <1000> was not: <1000>

Solution

  • assertSame tests that the two objects are the same objects, i.e. that they are ==:

    Asserts that two objects refer to the same object. If they are not the same, an AssertionError without a message is thrown.

    In your case, since bd1 and bd2 are both new BigDecimal, the objects aren't the same, hence the exception.

    What you want is to use assertEquals, that tests if two objects are equal, i.e. .equals:

    Asserts that two objects are equal. If they are not, an AssertionError without a message is thrown. If expected and actual are null, they are considered equal.

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