What exactly does assertEquals check for when asserting lists?

吃可爱长大的小学妹 提交于 2019-12-23 09:48:58

问题


In my test I'm asserting that the list I return is an alphabetically ordered list of the one I just created.

What exactly does the assertEquals do check for? Does it check the ordering of the list or just its contents?

So if I have a list of { "Fred", "Bob", "Anna" } would list 2 of { "Anna", "Bob", "Fred" } return true as they contain the same object, regardless of order?


回答1:


If you follow the source code of jUnit. You will see that assertEquals eventually calls the equals method on the objects provided in the the isEquals method.

private static boolean isEquals(Object expected, Object actual) {
    return expected.equals(actual);
}

Source Code: https://github.com/junit-team/junit/blob/master/src/main/java/org/junit/Assert.java

This will call the .equals() method on the implementation of List. Here is the source code for the .equals() implementation of `ArrayList'.

ArrayList.equals()

  public boolean equals(Object o) {
      if (o == this) //Equality check
          return true;
      if (!(o instanceof List))  //Type check
          return false;
      ListIterator<E> e1 = listIterator();
      ListIterator e2 = ((List) o).listIterator();
      while(e1.hasNext() && e2.hasNext()) {
          E o1 = e1.next();
          Object o2 = e2.next();
          if (!(o1==null ? o2==null : o1.equals(o2))) //equality check of list contents
              return false;
      }
      return !(e1.hasNext() || e2.hasNext());
  }



回答2:


There is no special assertEquals functions in junit.framework.Assert which accepts List or Collection object.

When you say assertEquals(list1, list2); it simply checks whether list1.equals(list2) and if not throws AssertionError




回答3:


A List is by definition ordered, so I would say it calls equals() and check the elements of both lists one by one.

Ok let me rephrase, what do you mean by "the ordering of the list" and "its content"?

If the list you create is [b,a], the ordered one will be [a,b]. [a,b] can only be equal to [a,b] because a List is ordered.

Two sets, [a,b] and [b,a] are not ordered but equal.

Plus if you look at the source, it DOES call equals(), so why the downvotes?



来源:https://stackoverflow.com/questions/16788275/what-exactly-does-assertequals-check-for-when-asserting-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!