Java Reference
In-Depth Information
assert objects implementing
java.lang.Comparable
(numbers happen to be a subset
of such objects). For instance, to assert that a variable
x
is greater than 42, we'd write
ComparableAssert.assertGreater(42, x);
And in the case of failure, the message would be
junit.framework.AssertionFailedError: expected greater than:<42> but was:<23>
The next interesting class is
ListAssertions
, which, as the name implies, provides
methods to verify lists. More specifically, it has only two methods:
assert
Equals
(List,
List)
and
assertContains(List,
Object)
.
11
Before we see them in action,
let's define a few
List
fixtures:
List<Integer> LIST1 = Arrays.asList(4, 8, 15, 16, 23, 42);
List<Integer> LIST2 = Arrays.asList(108);
List<Integer> LIST3 = Arrays.asList(4, 8, 15, 16, 42, 23);
List<Integer> LIST4 = Arrays.asList(4, 8, 15, 16, 108, 23);
The first list (
LIST1
) contains six random numbers and is the list that will be com-
pared with a list with a different number of elements (
LIST2
), a list with the same ele-
ments but in a different order (
LIST3
), and a list with the same number of elements
but some different ones (
LIST4
).
If you used
JU
nit's
assertEquals()
method to compare
LIST1
and
LIST4
, the mes-
sage would be
java.lang.AssertionError: expected:<[4, 8, 15, 16, 23, 42]> but was:
➥
<[4, 8, 15, 16, 108, 23]>
Although the message contains a clear description of the list's content, it's not easy to
realize why they aren't equal. The reason is that
JU
nit's
assertEquals()
method treats
the list as any other object, delegating its message formatting to Java's
String
class.
If we used the
JU
nit-addons alternative (
ListAssert.assertEquals()
) instead,
the result would be
junit.framework.AssertionFailedError: expecting <42> in
➥
<4, 8, 15, 16, 108, 23>
That's a better message, although it doesn't inform us as to where the lists are differ-
ent, only that one element is missing. The way the method works, it would fail to
detect that
LIST1
and
LIST3
are different, because they have the same elements but in
different order. It sounds like a bug, but it's a design decision, as stated in the Javadoc:
“Asserts that two lists are equal (the order is not relevant).”
12
If the lists have different
sizes (like
LIST1
and
LIST2
), the message is even more confusing:
junit.framework.AssertionFailedError: expecting <4> in <108>
11
Technically speaking, it provides four methods, because each assert method has an overloaded version that
also takes a message.
12
It's still a conceptual bug; such behavior would make more sense comparing sets.