Search code examples
javajunitcloning

How to JUnit test my cloning method?


I have a clone method in my Student class and I'm trying to test if it is working as expected (dob and address and deep cloned and course is shallow cloned)

I need help with the second chunk of code, I'm not sure how to correctly test if address and dob are deep cloned and course is shallow cloned

...

public Student clone() {
    Student clone = new Student();
    clone.dob = (Date) this.dob.clone();
    clone.address = this.address.clone();
    clone.course = this.course;
    return clone;
}

...

public void testCloning() {
    Student test = clone?
    assertEquals(Student, Student.clone())
}

Solution

  • If you want to test in this way, you should override equals() and hashcode() methods by specifying all fields you want to clone.

    Now, is suitable and effective to override equals() and hashcode() with all fields if a more elementary information can identify one Student instance ?

    As alternative way would be to compare that values of the fields are the same with field accessors.
    Besides, fields with deep cloning should also be asserted by checking that objects are not the same and fields with shallow cloning could be simply asserted by checking that objects are the same.

    You could do it for example :

    @Test
    public void cloning() {
        Student original = new Student(....); // 
        ...
        Student cloned = original.clone();
        // deep check
        assertEquals(original.getDob(), cloned.getDob());
        assertEquals(original.getAddress(), cloned.getAddress());
        assertNotSame(original.getDob(), cloned.getDob());
        assertNotSame(original.getAddress(), cloned.getAddress());
    
       // shallow check    
       assertSame(original.getCourse(), cloned.getCourse());
    }