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>
math. BigDecimal. equals() method checks for equality of a BigDecimal value with the object passed. This method considers two BigDecimal objects equal if only if they are equal in value and scale.
The official junit solution to assert that two BigDecimal are matematically equal is to use hamcrest.
With java-hamcrest 2.0.0.0 we can use this syntax:
// import static org.hamcrest.MatcherAssert.assertThat; // import org.hamcrest.Matchers; BigDecimal a = new BigDecimal("100") BigDecimal b = new BigDecimal("100.00") assertThat(a, Matchers.comparesEqualTo(b));
Hamcrest 1.3 Quick Reference
assertSame
checks if both objects are the same instance. assertEquals
checks if the numbers are equal in value and scale, that means i.e. 1000 is not equal to 1000.00. If you want to compare only the numeric value, you should use compareTo()
method from BigDecimal
.
For example:
BigDecimal bd1 = new BigDecimal (1000.00); BigDecimal bd2 = new BigDecimal (1000); org.junit.Assert.assertTrue(bd1.compareTo(bd2) == 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With