Reputation: 11020
In Junit 4, do you see any drawback to throw a ComparisonFailure
instead of an AssertionError
when assertEquals(Object, Object) fails ?
assertEquals(Object, Object) throws
ComparisonFailure
if both expected and actual are StringAssertionError
if either is not a StringAssertionError
message is already of the form
"expected:<"+ expected.toString() +"> but was <"+ actual.toString()
(via String.valueOf
, see below junit-4.8.2 method invoked by Assert.assertEquals(Object, Object) to build AssertionError message):
static String format(Object expected, Object actual) {
...
String expectedString= String.valueOf(expected);
String actualString= String.valueOf(actual);
...
return formatted+"expected:<"+ expectedString +"> but was:<"+ actualString +">";
ComparisonFailure
provide far more readable way to spot the differences in dialog box of eclipse or Intellij IDEA (FEST-Assert throws this exception)
[Update: question edited to focus on ComparisonFailure/AssertionError discussion.]
Upvotes: 11
Views: 4723
Reputation: 5011
We started with comparing strings because it was obvious how to make the error message more helpful. We never expanded ComparisonFailure to general objects because it wasn't clear how to do so in a general way. As other have suggested, you're welcome to add special assertions if you can provide better error messages or move to Hamcrest, which provides a general mechanism for adding useful failure messages.
Regards,
Kent
Upvotes: 10
Reputation: 105043
I agree with current JUnit implementation, with two exception classes. Mostly because it gives us an ability to differentiate comparison problems (ComparisonFailure
) and more "severe" type incompatibility problems (AssertionError
).
In general, text message inside an Exception
is just a helper for a human being, and is not meant to be touched by any software tools. That's why type of thrown exception is the only indicator of the problem happened.
Upvotes: 0
Reputation: 91871
I think you can certainly write your own substitute assertEquals method to do that without any significant problems, if that works for you.
However, in the general case (from the point of view of the framework developers), is it a good idea, I'm not sure. Often the failure objects won't have a toString implmentation, at which point the failure message from the IDE will be very misleading. You would get the impression that the comparison was on reference identity, when it may not have been.
In other words, it is valuable if the objects have a meaningful toString implementation, otherwise it may not be.
Upvotes: 2