Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 用于复杂对象的apache EqualBuilder_Java_Unit Testing_Reflection_Comparison_Apache Commons - Fatal编程技术网

Java 用于复杂对象的apache EqualBuilder

Java 用于复杂对象的apache EqualBuilder,java,unit-testing,reflection,comparison,apache-commons,Java,Unit Testing,Reflection,Comparison,Apache Commons,我试图比较两个结构复杂的对象,但apache EqualsBuilder.reflectionEquals无法比较这两个对象。你能告诉我我错过了什么吗。结果返回false import org.apache.commons.lang.builder.EqualsBuilder; public class Test { public static void main(String[] args){ FirstLevel firstLevel1 = new FirstLe

我试图比较两个结构复杂的对象,但apache EqualsBuilder.reflectionEquals无法比较这两个对象。你能告诉我我错过了什么吗。结果返回false

import org.apache.commons.lang.builder.EqualsBuilder;

public class Test {
    public static void main(String[] args){

        FirstLevel firstLevel1 = new FirstLevel("string1", "string2", new SecondLevel("line1"));
        FirstLevel firstLevel12 = new FirstLevel("string1", "string2", new SecondLevel("line1"));

        System.out.print(EqualsBuilder.reflectionEquals(firstLevel1, firstLevel12, true));
    }
}

class FirstLevel{

    String line1;
    String line2;
    SecondLevel secondLevel;

    FirstLevel(String line1, String line2, SecondLevel secondLevel) {
        this.line1 = line1;
        this.line2 = line2;
        this.secondLevel = secondLevel;
    }
}

class SecondLevel{
    String level2Line1;


    SecondLevel(String level2Line1) {
        this.level2Line1 = level2Line1;
    }
}

EqualsBuilder.reflectionEquals
方法无法通过反射将相同的相等性测试应用于SecondLevel类字段。您需要在第二级类中重写
equals
(因此
hashCode
)才能通过此操作

如果您不能覆盖equals,并且很乐意向项目添加另一个依赖项,那么您还可以查看Unitils库中的
ReflectionAssert.assertReflectionEquals
方法:


但是如果我不能控制课堂怎么办?我不能使用extends,因为类是紧密耦合的。您可以在FirstLevel和SecondLevel之外的测试实用程序类中定义一个equals方法,该方法基于FirstLevel的两个实例之间的相等性来测试值?您还可以查看Unitils库中的ReflectionAssert.assertReflectionEquals-我已经用链接到它。谢谢安妮。我在对象中有100个字段,它非常复杂。是的,unitils看起来很有前途,而且工作也很好。但是我的项目中有ApacheCommons作为依赖项,我只是想尝试一下ApacheCommons:)