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?
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With