|
| 1 | +package com.yanimetaxas.realitycheck; |
| 2 | + |
| 3 | +import static org.junit.Assert.assertNotNull; |
| 4 | + |
| 5 | +import java.io.Serializable; |
| 6 | +import java.math.BigDecimal; |
| 7 | +import java.util.Currency; |
| 8 | +import org.junit.Test; |
| 9 | + |
| 10 | +/** |
| 11 | + * @author yanimetaxas |
| 12 | + * @since 24-Mar-18 |
| 13 | + */ |
| 14 | +public class ObjectCheckTest { |
| 15 | + |
| 16 | + @Test |
| 17 | + public void objectIsEqualTo() throws Exception { |
| 18 | + Object object = new Object(); |
| 19 | + assertNotNull(new ObjectCheck(object).isEqualTo(object)); |
| 20 | + } |
| 21 | + |
| 22 | + @Test(expected = AssertionError.class) |
| 23 | + public void objectIsEqualTo_WhenIsNot() throws Exception { |
| 24 | + Object object1 = new Object(); |
| 25 | + Object object2 = new Object(); |
| 26 | + assertNotNull(new ObjectCheck(object1).isEqualTo(object2)); |
| 27 | + } |
| 28 | + |
| 29 | + @Test |
| 30 | + public void customObjectIsEqualTo() throws Exception { |
| 31 | + Money money = new Money(new BigDecimal(10.1), Currency.getInstance("EUR")); |
| 32 | + assertNotNull(new ObjectCheck(money).isEqualTo(money)); |
| 33 | + } |
| 34 | + |
| 35 | + @Test(expected = AssertionError.class) |
| 36 | + public void customObjectIsEqualTo_WhenIsNot() throws Exception { |
| 37 | + Money moneyEUR = new Money(new BigDecimal(10.1), Currency.getInstance("EUR")); |
| 38 | + Money moneySEK = new Money(new BigDecimal(10.1), Currency.getInstance("SEK")); |
| 39 | + assertNotNull(new ObjectCheck(moneyEUR).isEqualTo(moneySEK)); |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +class Money implements Serializable, Comparable<Money> { |
| 44 | + |
| 45 | + private BigDecimal amount; |
| 46 | + private Currency currency; |
| 47 | + |
| 48 | + Money(BigDecimal amount, Currency currency) { |
| 49 | + this.amount = amount; |
| 50 | + this.currency = currency; |
| 51 | + } |
| 52 | + |
| 53 | + private BigDecimal getAmount() { |
| 54 | + return amount; |
| 55 | + } |
| 56 | + |
| 57 | + @Override |
| 58 | + public int compareTo(Money obj) { |
| 59 | + return getAmount().compareTo(obj.getAmount()); |
| 60 | + } |
| 61 | + |
| 62 | + @Override |
| 63 | + public boolean equals(Object o) { |
| 64 | + if (this == o) { |
| 65 | + return true; |
| 66 | + } |
| 67 | + if (o == null || getClass() != o.getClass()) { |
| 68 | + return false; |
| 69 | + } |
| 70 | + Money money = (Money) o; |
| 71 | + |
| 72 | + return amount.equals(money.amount) && currency.equals(money.currency); |
| 73 | + } |
| 74 | + |
| 75 | + @Override |
| 76 | + public int hashCode() { |
| 77 | + int result = amount.hashCode(); |
| 78 | + result = 31 * result + currency.hashCode(); |
| 79 | + return result; |
| 80 | + } |
| 81 | +} |
0 commit comments