I liked JaredPar's idea but I didn't want to pass in Console.Out
and Console.Error
to every helper output method I had. However, my output does go through a single class, so I just set a couple static fields in it:
internal static TextWriter _stdOut = Console.Out;
internal static TextWriter _stdErr = Console.Error;
I updated my output methods in the output handler class to make use of these fields. I then updated that project's AssemblyInfo.cs to include:
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("MyTestProject")]
This way, I can override _stdOut
and _stdErr
in my test methods, call my method to be tested (which uses my output handling class), and confirm the output I expected.
OutputHandler._stdOut = new StringWriter();
MySnazzyMethod("input", 1, 'c');
OutputHandler._stdOut.Flush();
string expected = "expected output";
string stdout = OutputHandler._stdOut.ToString().Trim(new[] { '\r', '\n' });
Assert.IsFalse(string.IsNullOrEmpty(stdout));
Assert.AreEqual(expected, stdout);