如何在执行MSTest测试期间写入Console.Out

时间:2011-02-03 08:59:40

标签: c# console mstest watin

上下文:
我们的一些用户在我们的Web应用程序中报告了文件上传功能的问题。它只是偶尔发生,没有任何特殊模式。我们一直试图解决这个问题,在我们认为可能有用的任何地方添加调试信息,爬行日志等,但我们无法重现或弄清楚它。

问题:
我现在正试图通过使用MSTest和WatiN来重现这个应该重复失败很多次(几百次)的操作。只是想知道测试循环中有多远,我想打印一些类似的东西:

Console.WriteLine(String.Format("Uploaded file, attempt {0} of {1}", i, maxUploads));

然而,这不会出现在“输出”窗口中。现在我知道你将在测试结果中获得控制台输出(以及从Debug.Writeline输出的内容等),但是在测试结束后才能使用它。由于我的测试有数百次重复可能需要一段时间,所以我想知道它已经走了多远。

问题:
有没有办法在测试执行期间在输出窗口中获取控制台输出?

5 个答案:

答案 0 :(得分:103)

未出现控制台输出是因为后端代码未在测试环境中运行。

最好使用Trace.WriteLine(在System.Diagnostics中),然后添加一个写入文件的跟踪侦听器。

This topic from MSDN显示了这样做的方法。


根据Marty Neal和Dave Anderson的评论:

using System;
using System.Diagnostics;

...

Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
// or Trace.Listeners.Add(new ConsoleTraceListener());
Trace.WriteLine("Hello World");

答案 1 :(得分:69)

使用Debug.WriteLine。这将立即在Output窗口中显示您的消息。唯一的限制是您必须以Debug模式运行测试。

[TestMethod]
public void TestMethod1()
{
    Debug.WriteLine("Time {0}", DateTime.Now);
    System.Threading.Thread.Sleep(30000);
    Debug.WriteLine("Time {0}", DateTime.Now);
}

<强>输出

enter image description here

答案 2 :(得分:13)

我找到了自己的解决方案。我知道Andras的答案可能与MSTEST最为一致,但我不想重构我的代码。

[TestMethod]
public void OneIsOne()
{
    using (ConsoleRedirector cr = new ConsoleRedirector())
    {
        Assert.IsFalse(cr.ToString().Contains("New text"));
        /* call some method that writes "New text" to stdout */
        Assert.IsTrue(cr.ToString().Contains("New text"));
    }
}

一次性ConsoleRedirector定义为:

internal class ConsoleRedirector : IDisposable
{
    private StringWriter _consoleOutput = new StringWriter();
    private TextWriter _originalConsoleOutput;
    public ConsoleRedirector()
    {
        this._originalConsoleOutput = Console.Out;
        Console.SetOut(_consoleOutput);
    }
    public void Dispose()
    {
        Console.SetOut(_originalConsoleOutput);
        Console.Write(this.ToString());
        this._consoleOutput.Dispose();
    }
    public override string ToString()
    {
        return this._consoleOutput.ToString();
    }
}

答案 3 :(得分:3)

我遇到了同样的问题而且我是#34;跑步&#34;测试。如果我改为&#34; Debug&#34; Debug输出显示的测试就像所有其他Trace和Console一样好。 如果你&#34; Run&#34;我不知道如何查看输出。测试。

答案 4 :(得分:0)

您最好设置一个测试并通过此测试创建性能测试。这样,您可以使用默认工具集监控进度。