简体   繁体   English

在两个对象上的assertEquals()

[英]assertEquals() on two objects

When comparing two objects using assertEquals() does it considering looking into the internal structure viz. 当使用assertEquals()比较两个对象时,是否要考虑内部结构,即。 the properties of the objects? 对象的属性?

Suppose I have a class A like following: 假设我有一个如下的A类:

public class A {
    private int ID;
    private String name;
    private String address;
}

And suppose the supplied object's (that is to be compared to an object of A ) properties are in a different order, then what will assertEquals() do? 并假设所提供的对象(将与A的对象进行比较)的属性的顺序不同,那么assertEquals()做什么? Is there a robust method to do it the other way? 有一种健壮的方法可以做到这一点吗?

@JimGarrison is quite right - assertEquals() will just call the equals() method on your objects to determine equality. @JimGarrison是非常正确的-assertEquals assertEquals()只会在对象上调用equals()方法来确定相等性。

To answer your question, " Is there a robust method to do it the other way? ", if you can't properly implement the equals() method on your class for whatever reason, and you want to evaluate the equality of objects based on the values of their fields, consider using EqualsBuilder's reflectionEquals() method . 要回答您的问题,“ 是否有一种健壮的方法可以这样做? ”,如果由于某种原因您不能在类上正确实现equals()方法,并且您想根据它们字段的值,请考虑使用EqualsBuilder的reflectEquals reflectionEquals()方法 It is fairly robust, and allows you to exclude whatever fields you want. 它相当健壮,并且允许您排除所需的任何字段。

To answer your other question, " suppose the supplied object's properties are in a different order, then what will assertEquals() do? ", all it will do is call the equals() method on the other instance. 要回答另一个问题,“ 假设提供的对象的属性顺序不同,那么assertEquals()会做什么? ”,它要做的就是在另一个实例上调用equals()方法。 For example, if you call assertEquals(a, b) , then that will eventually call a.equals(b) . 例如,如果调用assertEquals(a, b) ,则最终将调用a.equals(b) However, if you call assertEquals(b, a) , then that will eventually call b.equals(a) . 但是,如果调用assertEquals(b, a) ,则最终将调用b.equals(a)

I hope that helps. 希望对您有所帮助。

Assert.assertEquals() will use the class' equals() method. Assert.assertEquals()将使用类的equals()方法。

If your class overrides equals() to do a deep comparison then that's what will be used. 如果您的类重写equals()进行深度比较,则将使用该类。 If you don't override equals() then you'll get Object#equals() based on identity equality only. 如果不重写equals()则仅基于身份相等性将获得Object#equals()

In other words, YOU decide what equals() means. 换句话说,您决定equals()含义。

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

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