Click here to Skip to main content
Click here to Skip to main content

Getting Console Output Within A Unit Test

, 3 Dec 2012
Rate this:
Please Sign up or sign in to vote.
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:

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:

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:

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)

About the Author

Vasil Trifonov
Software Developer (Senior) Telerik
Bulgaria Bulgaria
No Biography provided
Follow on   Twitter   Google+

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 4 Dec 2012
Article Copyright 2012 by Vasil Trifonov
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid