从单元测试中抓取发送到Console.Out的输出?

ang*_*son 43 c# console nunit unit-testing

我正在使用NUnit在C#中构建单元测试,并且我想测试主程序实际上输出正确的输出,具体取决于命令行参数.

有没有办法从NUnit测试方法,调用Program.Main(...)抓取写入Console.Out和Console.Error的所有内容,以便我可以验证它?

Mar*_*ann 70

您可以将Console In,Out和Error重定向到自定义StringWriters,就像这样

[TestMethod]
public void ValidateConsoleOutput()
{
    using (StringWriter sw = new StringWriter())
    {
        Console.SetOut(sw);

        ConsoleUser cu = new ConsoleUser();
        cu.DoWork();

        string expected = string.Format("Ploeh{0}", Environment.NewLine);
        Assert.AreEqual<string>(expected, sw.ToString());
    }
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此博客文章.

  • @EgorPavlikhin:您应在每次测试结束时使用`Console.SetOut(new StreamWriter(Console.OpenStandardError())`(您可能还需要将“ Autoflush`设置为true”)重置标准输出。与任何测试运行程序一起使用,包括R#。 (2认同)

Vas*_*nov 12

您可以使用此简单类通过using语句获取输出:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是如何使用它的示例:

using (var consoleOutput = new ConsoleOutput())
{
    target.WriteToConsole(text);

    Assert.AreEqual(text, consoleOutput.GetOuput());
}
Run Code Online (Sandbox Code Playgroud)

您可以在我的博客文章中找到更多详细信息和工作代码示例 - 在单元测试中获取控制台输出.

  • 安德鲁,我认为这个答案可能符合此处列出的可接受标准 https://meta.stackexchange.com/questions/94022/how-can-i-link-to-an-external-resource-in-a-community-friend -way 还可以表明以“您尚未阅读”开头不太友好。您可以建议他们阅读带有链接的常见问题解答:) https://meta.stackexchange.com/questions/7931/faq-for-stack-exchange-sites (5认同)
  • 您还没有阅读自我推广常见问题解答.您发布的每个答案都是指向您博客的链接. (2认同)