Вопрос

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.

Это было полезно?

Решение

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.

Другие советы

You can use field based templates of Fast code ecllipse plugin .You can write a simple template and select many fields you want, from a class, to generate the statements using those fields.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top