Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does assertEquals(Object o1, Object o2) uses the equals method

Tags:

java

junit

In other words, does assertEquals works with a class that overrides equals

like image 655
Jerome Avatar asked Nov 28 '12 14:11

Jerome


People also ask

How does assertEquals work for 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.

Does object have an equals method?

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y , this method returns true if and only if x and y refer to the same object ( x == y has the value true ).

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 do you use equals method in Java for objects?

If the two objects have the same values, equals() will return true . In the second comparison, equals() checks to see whether the passed object is null, or if it's typed as a different class. If it's a different class then the objects are not equal. Finally, equals() compares the objects' fields.


2 Answers

From the source code of the assertEquals method that you can find on the Junit GitHub Repo:

/**  * Asserts that two objects are equal. If they are not  * an AssertionFailedError is thrown with the given message.  */ static public void assertEquals(String message, Object expected, Object actual) {     if (expected == null && actual == null) {         return;     }     if (expected != null && expected.equals(actual)) {         return;     }     failNotEquals(message, expected, actual); } 

You can see that Junit is using the .equals() method.

Edit:

The code snippet is coming from a deprecated version of Junit.

You can read about the source of the 'new' Junit here. The idea is pretty much the same, the .equals() method is also used.

like image 159
Timothée Jeannin Avatar answered Oct 17 '22 08:10

Timothée Jeannin


does assertEquals works with a class that overrides equals?

Yes, assertEquals() invokes the overridden equals() if the class has one.

like image 30
Juvanis Avatar answered Oct 17 '22 09:10

Juvanis