Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why junit ComparisonFailure is not used by assertEquals(Object, Object)?

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

  • a ComparisonFailure if both expected and actual are String
  • an AssertionError if either is not a String

AssertionError 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.]

like image 736
Philippe Blayo Avatar asked Dec 31 '10 16:12

Philippe Blayo


2 Answers

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

like image 156
Kent Beck Avatar answered Nov 10 '22 18:11

Kent Beck


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.

like image 33
Yishai Avatar answered Nov 10 '22 20:11

Yishai