[英]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. 我会用反思做这件事。
MyClass
. MyClass
实例。 (A) getClass().getDeclaredFields()
. getClass().getDeclaredFields()
来完成。 MyClass
. MyClass
的空白实例。 (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.