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.


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.


您可以使用快速代码ecllipse插件的基于字段的模板。您可以编写简单的模板,并从类中选择许多您希望使用这些字段生成语句的字段。

链接地址: http://www.djcxy.com/p/77486.html

上一篇: 为什么我的循环打印不像我期望从伪代码那样?

下一篇: 等于方法的Junit