Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 
like image 445
kAnGeL Avatar asked Feb 23 '16 09:02

kAnGeL


People also ask

How do you know if two Bigdecimals are equal?

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.


2 Answers

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

like image 99
frhack Avatar answered Sep 29 '22 04:09

frhack


assertSamechecks if both objects are the same instance. assertEqualschecks 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);  
like image 36
Endery Avatar answered Sep 29 '22 05:09

Endery