Search code examples
c#unit-testingconsolexunit.net

How to do unit test console output with xUnit.net?


I have a method that prints private variable of the class.

public class Test
{
    private int number;

    public Test(int number)
    {
        this.number = number;
    }

    public void PrintValue()
    {
        Console.WriteLine("Number: " + number);
    }
}

How can I create an unit test to make sure it prints value I expected on console?


Solution

  • Make console output a dependency. Since Console.WriteLine will redirect its output to Console.Out property, all you need is TextWriter instance:

    public Test(TextWriter outputWriter, int number)
    {
        this.outputWriter = outputWriter;
        this.number = number;
    }
    
    public void PrintValue()
    {
        outputWriter.WriteLine("Number: " + number);
    }
    

    In real application, you pass it Console.Out to print to system console. In test, you simply use fake writer (for example StringWriter based on StringBuilder):

    const int NumberToPrint = 5;
    var content = new StringBuilder();
    var writer = new StringWriter(content);
    var sut = new Test(writer, NumberToPrint);
    
    sut.PrintNumber();
    
    var actualOutput = content.ToString();
    Assert.AreEqual(actualOutput, "Number: 5");