How to write a unit test to check copy constructor is in sync with class properties?

Viewed 1382

Recently we had a bug in our system that is caused by forgetting to assign a newly added class property in the copy constructor.

For example:

public class MyClass {

    private Long companyId;
    private Long classId;
    private Double value;   <=  newly added

    public MyClass(MyClass myClass) {
        this.setCompanyId(myClass.getCompanyId());
        this.setClassId(myClass.getClassId());
        this.setValue(myClass.getValue());   <= we forget this line
    }

I want to write a unit test that guarantees to catch the missing copy assignment when a new property is added. How should I proceed with this?

1 Answers

I'd do this with reflection.

  • New up an instance of MyClass. (A)
  • Through reflection, assign a value to every field. This can be accomplished with getClass().getDeclaredFields().
  • New up a blank instance of MyClass. (B)
  • Run the copy constructor on A against B.
  • Through reflection, determine if the fields in A are equal to B.
Related