1

For example:

public class Fruit{ private String color; private double weight; ... public boolean equals(Fruit a){ return (this.getColor().equals(a.getColor()) && (this.getWeight()==a.getWeight())); } } public class Orange extends Fruit{ public Orange(double weight) { super("orange", weight); } } public class NavalOrange extends Orange{ public NavalOrange(double weight) { super(weight); } } 

Then I wrote a test about this to check two objects if they are same.

 Orange orange = new Orange(8); NavalOrange navalOrange = new NavalOrange(8); assertEquals(orange, navalOrange); 

But it just keeps returning errors:

 junit.framework.AssertionFailedError: expected:<Orange@5305068a> but was:<NavalOrange@1f32e575> 

Can anyone explain why this is happening? I think it may be something wrong at the toString method.

1
  • 1
    Your equals must take an object as a parameter; jUnit won't find it if you require a fruit. If you are using eclipse, try rightclicking on your Fruit class and selecting Generate equals() and hashcode(). Commented Oct 20, 2014 at 1:07

1 Answer 1

2

There is no equals(Fruit) method in Object. You equals method should start with something like...

@Override public boolean equals(Object a) { boolean equals = false; if (a instanceof Fruit) { ... } return equals; } 

Basically, all assertEquals is doing is using Object#equals. You can test this by adding the @Override annotation to your equals method and it will produce a compiler error, as `equals(Fruit) does not override any method from it's parent...

Also, if you override equals, you should override hashCode in order to maintain it's contract...

From the JavaDocs for Object#equals

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.