Over the years, I have written many test cases that submit long Strings to Assert.assertEquals(String, String, String). When they are not equal, then it becomes very difficult to figure out exactly what is different. The AssertionError message simply repeats the String parameters. I then have to manually search for the difference. This is time consuming.
Instead, please implement the method as follows.
public static void assertEquals(String actual, String expect, String message)
{
String actualLine, expectLine;
char actualChar, expectChar;
int index, length;
length = Math.min(actual.length(), expect.length());
for (index = 0; index < length; index++)
{
actualChar = actual.charAt(index);
expectChar = expect.charAt(index);
if (actualChar == expectChar)
{
continue;
}
actualLine = getLine(actual, index);
expectLine = getLine(expect, index);
throw new AssertionError
(
message +
"\nDiff at " + index +
"\nActual Char: " + actualChar + " (" + (int) actualChar + ')' +
"\nExpect Char: " + expectChar + " (" + (int) expectChar + ')' +
"\nActual Line: " + actualLine +
"\nExpect Line: " + expectLine +
"\nBefore Diff: " + actual.substring(Math.max(index - 20, 0), index) +
"\n\nActual:\n\n" + actual +
"\n\nExpect:\n\n" + expect
);
}
if (actual.length() != expect.length())
{
throw new AssertionError
(
message +
"\nThe lengths differ." +
"\nActual Length: " + actual.length() +
"\nExpect Length: " + expect.length() +
"\n\nActual:\n\n" + actual +
"\n\nExpect:\n\n" + expect
);
}
}
The above gives the following output:
java.lang.AssertionError: Transform JSON
Diff at 96
Actual Char: N (78)
Expect Char: R (82)
Actual Line: 0,,0,0.000,0.000,0,0,"Not Root"
Expect Line: 0,,0,0.000,0.000,0,0,"Root"
Before Diff: ,0,0.000,0.000,0,0,"
Actual:
ID,Parent ID,Depth,Name
0,,0,"Not Root"
Expect:
ID,Parent ID,Depth,Name
0,,0,"Root"
The above output makes it easy to figure out what the difference is.
Note: The header of lines 2-6 are the same length to make it very quick to visually find the difference.
Note: The actual and expect were truncated for brevity. In reality, these Strings are 12 long lines. The number of lines and length of the lines makes it hard to find the difference.
Over the years, I have written many test cases that submit long Strings to Assert.assertEquals(String, String, String). When they are not equal, then it becomes very difficult to figure out exactly what is different. The AssertionError message simply repeats the String parameters. I then have to manually search for the difference. This is time consuming.
Instead, please implement the method as follows.
The above gives the following output:
The above output makes it easy to figure out what the difference is.
Note: The header of lines 2-6 are the same length to make it very quick to visually find the difference.
Note: The actual and expect were truncated for brevity. In reality, these Strings are 12 long lines. The number of lines and length of the lines makes it hard to find the difference.