我正在开发一个将一个类的数据复制到另一个类的应用程序。
我正在尝试测试getter-setter
方法是否正常。为了改进test coverage
,我正在制作一些类和方法,使用podamfactory
来填充给定班级成员中的数据。
然后我使用apache BeanUtils
将该对象的数据复制到其他对象。
然后我断言两个对象检查两者是否有相同的数据!
我面临的问题是: 我创建了3个类:
- Starter.java [有运行应用程序的主要方法]
- ChildClass.java [只有1个成员,即字符串集合及其getter方法和添加方法以在该成员中添加数据]
- ParentClass.java [在此类ChildClass'实例中已经创建并实例化了相关的getter和setter方法。还有hashcode和equals方法]
醇>
代码:
public class Starter {
static final PodamFactory factory = new PodamFactoryImpl();
public static void main(String[] args) throws Exception {
System.out.println("Start");
testClasses(ParentClass.class);
System.out.println("End");
}
public static void testClasses(final Class<?> klass) throws Exception {
final Object source = factory.manufacturePojo(klass);
final Object destination = klass.newInstance();
BeanUtils.copyProperties(destination, source);
Assert.assertEquals(source, destination);
Assert.assertNotEquals(source, new Object());
Assert.assertEquals(source.hashCode(), destination.hashCode());
}
}
在Main
方法中,我正在通过ParentClass
检查它的getter setter。 testClasses
方法执行复制和assertion
的主要工作。
当我调试时,我发现在copying properties
课后,子类的实例有列表,并且有5个成员。在这两个对象中,List
元素中有5个成员。
但是当我在ChildClass
中传递Main
时,请尝试调试我5 element
和source
中的destination
} 0 element
之后它有copying properties
。
所以我不理解BeanUtils
的这种行为,需要做什么如果我在ChildClass
中传递Main
时需要同样的工作?
当我通过ParentClass
时,它有不同的行为,当我通过ChildClass
时,它在Copying properties
中有不同的行为。
我创建了GitHub Repository来显示我的代码。您可以访问和检查我的应用程序的代码。
我为gradle
创建了简单的dependency management
项目。
如果有人了解更多信息,请告诉我。
感谢。
答案 0 :(得分:0)
BeanUtils遵循Java Bean意义上的属性的严格定义,即每个属性必须具有名称为 get 的getter +字段的名称和名称为 set 的setter + name of name一个领域。您的子类不包含setFields()setter。换句话说,你可以像这样改变它
public class ChildClass {
private final List<String> fields = new ArrayList<>();
public List<String> getFields() {
return this.fields;
}
public List<String> setFields(List<String> fields) {
this.fields = fields;
}
}
或者
public class ChildClass {
private final List<String> fields = new ArrayList<>();
public List<String> getFields() {
return this.fields;
}
public List<String> setFields(List<String> fields) {
this.fields.clear();
this.fields.addAll(fields);
}
}