Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit of equals method

I just want to know if there is a best practice or a common way to test equals implementation in objects. I mean test method that has been overridden.

public boolean equals(Object o)

I did using some logic like this. (Suppose number and name need to be equals to obtain true)

Dog d1 = new Dog(1,"Alvin");
Dog d2 = new Dog(2,"Alvin");

Assert.assertFalse(d1.equals(null));
Assert.assertFalse(d1.equals(d2));
d2.setId(1);
d2.setName("Kelvin");
Assert.assertFalse(d1.equals(d2));
d2.setName("Alvin");
Assert.assertTrue(d1.equals(d2));
Assert.assertTrue(d1.equals(d1));

But when there are a lot of fields this task is very large and boring, so my question is if there is any framework, tool, option, anything that makes this easier and can proof that method has been overridden correctly. thanks.

I know that override the method equals depends on the logic that you need, but also test case creation is, so looking for an standard way to test the method avoiding large codes in test cases, if there is exists obviously or any suggestion you might have.

like image 748
Koitoer Avatar asked Feb 16 '14 01:02

Koitoer


People also ask

How do you write the equal method in junit in Java?

String obj1="Junit"; String obj2="Junit"; assertEquals(obj1,obj2); Above assert statement will return true as obj1. equals(obj2) returns true.

What is equals () method in Java?

The equals() method compares two strings, and returns true if the strings are equal, and false if not.

How do you check if two objects are equal in junit?

Assert. assertEquals() methods checks that the two objects are equals or not. If they are not, an AssertionError without a message is thrown. Incase if both expected and actual values are null, then this method returns equal.

Does assertEquals use equal?

assertEquals() The assertEquals() method compares two objects for equality, using their equals() method.


1 Answers

Looking in the link of the duplicate question I read @user598656 answer and suggest to use MeanBeans (Automated java bean tester)

Reading the documentation I found this feature.

5.2.7. Property!Significance!Test!Algorithm! The property significance test algorithm is as follows:

for each property in public getter/setter method pairs do 
 create instance of class under test, object x 
 create instance of class under test, object y 
 change property of y to contain a different value 
 if property is insignificant then 
 assert x.equals(y) 
 else 
 assert x.equals(y) is false 
 end if 
end for 

It is what I was looking for, the answer is the last one but in my opinion this fit my needs.

like image 160
Koitoer Avatar answered Oct 18 '22 21:10

Koitoer