Issue
Using JUnit assertEquals()
, I am comparing strings which may differ in whitespace/control characters.
In particular, '\r\n' vs. '\n'.
When the strings differ in this way the error output from assertEquals()
is difficult to interpret for a few reasons.
- They are whitespace characters and are not suitable for visual inspection
- The \r character causes output to be overwritten.
This example shows how you'd normally test a string if you wouldn't have any special chars within */
@Test
public void testIfTheCarriageReturned()
{
final String expected = "we're taking\r\n the hobbits\r\n to Isengard!";
final String actual = "we're taking\n the hobbits\n to Isengard!";
assertEquals(expected, actual);
}
This example correctly determines that the strings differ but the output from JUnit does not make it clear how they differ (whitespace not being treated in any special way).
Is there a way to cause JUnit to produce more suitable output?
Solution
To be honest, I guess this not about formatting but rather about writing your tests properly. I've never cared about the new features of Junit5, therefore there might be a new super smart way to achieve this, but yeah:
@Test
public void testIfTheCarriageReturned()
{
/**
* This is how you'd normally test string if you wouldn't have any special chars within
*/
final String expected = "we're taking\r\n the hobbits\r\n to Isengard!";
final String linuxGuy = "we're taking\n the hobbits\n to Isengard!";
//assertEquals(expected, linuxGuy);
/**
* Just do it charwise...
*/
for(int i = 0; i<expected.length(); i++)
{
assertEquals("Character differed at index "+i,Character.getName(expected.charAt(i)), Character.getName(linuxGuy.charAt(i)));
}
}
This basically just gets the name for the character and compares whether they are equal at the same index.
This will lead to the following output:
org.junit.ComparisonFailure: Character differed at index 12 expected:<[CARRIAGE RETURN (CR])> but was:<[LINE FEED (LF])>
at org.junit.Assert.assertEquals(Assert.java:117)
Just to add: This will lead to a passed test when the actual String is longer than the expected String. You could either check the length afterwards or use the assertEquals method on the two strings after the loop. A matter of taste, I'd probably prefer the latter.
Answered By - maio290
Answer Checked By - Marie Seifert (JavaFixing Admin)