Automated unit testing for maintaining object method contracts in Java?
•
Java
When developing Java applications, I often rewrite object methods (usually equals and hashcode) I want some ways to systematically check whether I comply with the contract of object method in each course For example, I want to test to prove that hash codes are equal for equal objects I use JUnit testing framework, so it's better for me to want some JUnit solutions. I can automatically generate these tests, or some test cases, access all my courses and ensure that the contract is maintained
I use JDK6 and JUnit 4.4
Solution
public static void checkObjectIdentity(Object a1,Object a2,Object b1) {
public static void checkObjectIdentity(Object a1,Object a2,Object b1) { assertEquals(a1,a2); assertEquals(a2,a1); assertNotSame(a1,a2); assertEquals(a1.hashCode(),a2.hashCode()); assertFalse(a1.equals(b1)); assertFalse(a2.equals(b1)); assertFalse(b1.equals(a1)); assertFalse(b1.equals(a2)); }
Usage:
checkObjectIdentity(new Integer(3),new Integer(3),new Integer(4));
I can't think of anything better When you find an error, add a new call to checkobjectidentity
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码