Why junit ComparisonFailure is not used by assertEquals(Object, Object) ?
- by Philippe Blayo
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
@Test(expected=ComparisonFailure.class )
public void twoString() {
assertEquals("a String", "another String");
}
@Test(expected=AssertionError.class )
public void oneString() {
assertEquals("a String", new Object());
}
The two reasons why I ask the question:
ComparisonFailure provide far more readable way to spot the differences in dialog box of eclipse or Intellij IDEA (FEST-Assert throws this exception)
Junit 4 already use String.valueOf(Object) to build message "expected ... but was ..." (format method invoqued by Assert.assertEquals(message, Object, Object) in junit-4.8.2):
static String format(String message, Object expected, Object actual) {
...
String expectedString= String.valueOf(expected);
String actualString= String.valueOf(actual);
if (expectedString.equals(actualString))
return formatted + "expected: "
+ formatClassAndValue(expected, expectedString) +" but was: "
+ formatClassAndValue(actual, actualString);
else
return formatted +"expected:<"+ expectedString +"> but was:<"+ actualString +">";
Isn't it possible in assertEquals(message, Object, Object) to replace
fail(format(message, expected, actual));
by
throw new ComparisonFailure(message,
formatClassAndValue(expectedObject, expectedString),
formatClassAndValue(actualObject, actualString));
Do you see any compatibility issue with other tool, any algorithmic problem with that... ?