使控制台输出成为依赖项。由于Console.WriteLine
会将其输出重定向到Console.Out
property,因此您只需要TextWriter
实例:
public Test(TextWriter outputWriter, int number)
{
this.outputWriter = outputWriter;
this.number = number;
}
public void PrintValue()
{
outputWriter.WriteLine("Number: " + number);
}
在实际应用程序中,您将其传递Console.Out
给打印到系统控制台。在测试中,您只需使用假作家(例如StringWriter
基于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");