Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / DevOps / unit-testing

Getting Console Output Within A Unit Test

5.00/5 (5 votes)
4 Dec 2012CPOL 47.2K   77  
Getting console output within a unit test

Introduction

I needed to test a method which writes to the Console to validate the output. 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's say we have the following class we want to test:

C#
using System;

namespace ConsoleLogger
{
    public class DummyClass
    {
        public void WriteToConsole(string text)
        {
            Console.Write(text);
        }
    }
}

I have created a small helper class to redirect the output to a StringWriter:

C#
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();
        }
    }
}

Now let's write the unit test:

C#
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);
        }
    }
}

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)