Search code examples
javastringjunittostringassert

force assertEquals(String s, Object o) to use o.toString()?


Is it possible to force

assertEquals("10,00 €", new Currency(bon.getTotal()))

to use the toString() method of the Currency Object? (I don't want to call it myself.)

Since otherwise, it compares the references, which of course don't match.

java.lang.AssertionError:

expected: java.lang.String<10,00 €>

but was: jam.cashregister.Currency<10,00 €>

Update

I finally ended up with this code:

assertEquals(new Currency(bon.getTotal()), "10,00 €");

I don't know if it is a good idea to swap the expected with the actual part, in the assertation.

public class Currency() {

    @Override
    public boolean equals(Object other) {
        return this.toString().equals(other.toString());
    }
}

Solution

  • You should compare two instances of Currency:

    assertEquals(new Currency("10,00 €"), new Currency(bon.getTotal()))
    

    Therefore, redefining equals() is mandatory. If the equality must be based on the string representation of Currency, it's also mandatory to override toString() (you probably already did that).

    public class Currency {
    
        ...
    
        @Override
        public String toString() {
            //overriden in a custom way
        }
    
        @Override
        public boolean equals(Object other) {
            if(other instanceof Currency) {
                Currency that = (Currency) other;
                return this.toString().equals(that.toString());
            }
            return false;
        }
    
        ...
    }