Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit assertEquals( ) fails for two objects

Tags:

I created a class and overridden the equals() method. When I use assertTrue(obj1.equals(obj2)), it will pass the test; however, assertEquals(obj1, obj2) will fail the test. Could someone please tell the reason why?

like image 473
Terry Li Avatar asked May 19 '11 15:05

Terry Li


People also ask

Does assertEquals work with objects?

assertEquals. Asserts that two objects are equal. If they are not, an AssertionError is thrown with the given message. If expected and actual are null , they are considered equal.

How do you compare two objects in assertEquals?

assertEquals() calls equals() on your objects, and there is no way around that. What you can do is to implement something like public boolean like(MyClass b) in your class, in which you would compare whatever you want. Then, you could check the result using assertTrue(a. like(b)) .

How does junit assertEquals work?

assertEquals. Asserts that two objects are equal. If they are not, an AssertionError without a message is thrown. If expected and actual are null , they are considered equal.

How many parameters does assertEquals () have?

Procedure assertEquals has two parameters, the expected-value and the computed-value, so a call looks like this: assertEquals(expected-value, computed-value);


1 Answers

My guess is that you haven't actually overridden equals - that you've overloaded it instead. Use the @Override annotation to find this sort of thing out at compile time.

In other words, I suspect you've got:

public boolean equals(MyClass other) 

where you should have:

@Override // Force the compiler to check I'm really overriding something public boolean equals(Object other) 

In your working assertion, you were no doubt calling the overloaded method as the compile-time type of obj1 and obj2 were both MyClass (or whatever your class is called). JUnit's assertEquals will only call equals(Object) as it doesn't know any better.

like image 175
Jon Skeet Avatar answered Oct 12 '22 23:10

Jon Skeet