Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 425
Anonymous Avatar asked Jun 13 '12 16:06

Anonymous


1 Answers

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");
like image 75
k.m Avatar answered Sep 19 '22 17:09

k.m