简体   繁体   English

如何编写单元测试来检查复制构造函数是否与类属性同步?

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

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? 我该怎么办呢?

I'd do this with reflection. 我会用反思做这件事。

  • New up an instance of MyClass . 新建一个MyClass实例。 (A) (一种)
  • Through reflection, assign a value to every field. 通过反射,为每个字段分配一个值。 This can be accomplished with getClass().getDeclaredFields() . 这可以通过getClass().getDeclaredFields()来完成。
  • New up a blank instance of MyClass . 新建一个MyClass的空白实例。 (B) (B)
  • Run the copy constructor on A against B. 在A上运行复制构造函数。
  • Through reflection, determine if the fields in A are equal to B. 通过反射,确定A中的字段是否等于B.

You can override equals() method and use code snippet like that: 您可以覆盖equals()方法并使用如下代码片段:

MyClass a = new MyClass();
// set properties of a
MyClass b = new MyClass(a);
Assert.assertEquals(a, b); // check that a.equals(b) returns true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM