public
Last active — forked from Haacked/TestHelper.cs

String Comparison Unit Test Helper

  • Download Gist
TestHelper.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
public static class TestHelpers
{
public static void ShouldEqualWithDiff(this string actualValue, string expectedValue)
{
ShouldEqualWithDiff(actualValue, expectedValue, Console.Out);
}
 
public static void ShouldEqualWithDiff(this string actualValue, string expectedValue, TextWriter output)
{
if (actualValue.Equals(expectedValue, StringComparison.Ordinal)) return;
 
output.WriteLine("Idx Expected Actual");
output.WriteLine("---------------------");
int maxLen = Math.Max(actualValue.Length, expectedValue.Length);
for (int i = 0; i < maxLen; i++)
{
output.Write(i);
output.WritePadding(i);
if (i < actualValue.Length)
{
output.WriteCharInfo(actualValue[i]);
}
else
output.Write(" ");
output.Write("\t");
if (i < expectedValue.Length)
{
output.WriteCharInfo(expectedValue[i]);
}
else
output.Write(" ");
output.WriteLine();
}
output.WriteLine();
Assert.Equal(actualValue, expectedValue);
}
 
private static void WriteCharInfo(this TextWriter output, char c)
{
output.Write((int)c);
output.WritePadding(c);
output.Write(c.ToSafeString());
}
 
// Assumes strings smaller than 1000 chars. Typical with unit tests.
private static void WritePadding(this TextWriter output, int i)
{
output.Write(" ");
if (i < 100)
{
output.Write(" ");
}
if (i < 10)
{
output.Write(" ");
}
}
 
private static string ToSafeString(this char c)
{
if (Char.IsControl(c) || Char.IsWhiteSpace(c))
{
switch (c)
{
case '\r':
return @"\r";
case '\n':
return @"\n";
case '\t':
return @"\t";
case '\a':
return @"\a";
case '\v':
return @"\v";
case '\f':
return @"\f";
case ' ':
return @"\s";
default:
return String.Format("\\u{0:X};", (int)c);
}
}
return c.ToString(CultureInfo.InvariantCulture) + " ";
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.