OutputAssert.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using Xunit.Abstractions;
  2. namespace UnitTests;
  3. /// <summary>
  4. /// Provides xunit-style assertions for <see cref="ITestOutputHelper"/>.
  5. ///
  6. /// </summary>
  7. internal class OutputAssert
  8. {
  9. #pragma warning disable xUnit1013 // Public method should be marked as test
  10. /// <summary>
  11. /// Verifies two strings are equivalent. If the assert fails, output will be generated to standard output showing
  12. /// the expected and actual look.
  13. /// </summary>
  14. /// <param name="output"></param>
  15. /// <param name="expectedLook">
  16. /// A string containing the expected look. Newlines should be specified as "\r\n" as they will
  17. /// be converted to <see cref="Environment.NewLine"/> to make tests platform independent.
  18. /// </param>
  19. /// <param name="actualLook"></param>
  20. public static void AssertEqual (ITestOutputHelper output, string expectedLook, string actualLook)
  21. {
  22. // Convert newlines to platform-specific newlines
  23. expectedLook = ReplaceNewLinesToPlatformSpecific (expectedLook);
  24. // If test is about to fail show user what things looked like
  25. if (!string.Equals (expectedLook, actualLook))
  26. {
  27. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  28. output?.WriteLine (" But Was:" + Environment.NewLine + actualLook);
  29. }
  30. Assert.Equal (expectedLook, actualLook);
  31. }
  32. #pragma warning restore xUnit1013 // Public method should be marked as test
  33. private static string ReplaceNewLinesToPlatformSpecific (string toReplace)
  34. {
  35. string replaced = toReplace;
  36. replaced = Environment.NewLine.Length switch
  37. {
  38. 2 when !replaced.Contains ("\r\n") => replaced.Replace ("\n", Environment.NewLine),
  39. 1 => replaced.Replace ("\r\n", Environment.NewLine),
  40. _ => replaced
  41. };
  42. return replaced;
  43. }
  44. }