Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does assertEquals check for when asserting lists?

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?

like image 664
liloka Avatar asked May 28 '13 09:05

liloka


1 Answers

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());
  }
like image 93
Kevin Bowersox Avatar answered Oct 10 '22 00:10

Kevin Bowersox