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?
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());
}
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
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?