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.]
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With