Today I needed to test a method which writes to the Console to validate the ouput. It is not hard to change the default console output and check the result. However you may forget to return the original output at the end. So let's take a look at my solution.
Let say we have the following class we want to test:
I have created a small helper class to redirect the output to a StringWriter:
Now let's write the unit test:
This way we are sure that the original output will be restored and it's easy to get the output from the console.
You can find the sample here ConsoleLogger.zip.
Let say we have the following class we want to test:
1 2 3 4 5 6 7 8 9 10 11 12 | using System; namespace ConsoleLogger { public class DummyClass { public void WriteToConsole( string text) { Console.Write(text); } } } |
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 | using System; using System.IO; namespace ConsoleLogger.Tests { public class ConsoleOutput : IDisposable { private StringWriter stringWriter; private TextWriter originalOutput; public ConsoleOutput() { stringWriter = new StringWriter(); originalOutput = Console.Out; Console.SetOut(stringWriter); } public string GetOuput() { return stringWriter.ToString(); } public void Dispose() { Console.SetOut(originalOutput); stringWriter.Dispose(); } } } |
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 | using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ConsoleLogger.Tests { [TestClass] public class DummyClassTest { [TestMethod] public void WriteToConsoleTest() { var currentConsoleOut = Console.Out; DummyClass target = new DummyClass(); string text = "Hello" ; using (var consoleOutput = new ConsoleOutput()) { target.WriteToConsole(text); Assert.AreEqual(text, consoleOutput.GetOuput()); } Assert.AreEqual(currentConsoleOut, Console.Out); } } } |
You can find the sample here ConsoleLogger.zip.
No comments:
Post a Comment