我可以写入控制台单元测试?如果是的话,为什么不打开控制台窗口? [英] Can I write into console in a unit test? If yes, why the console window is not opened?

查看:308
本文介绍了我可以写入控制台单元测试?如果是的话,为什么不打开控制台窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Visual Studio中的测试项目。我用Microsoft.VisualStudio.TestTools.UnitTesting

I have a test project in Visual Studio. I use Microsoft.VisualStudio.TestTools.UnitTesting.

我在我的单元测试之一加入这一行:

I add this line in one of my unit tests:

Console.WriteLine("Some foo was very angry with boo");
Console.ReadLine();

当我运行测试,测试通过,但控制台窗口根本没有被打开。

When I run the test, test passes but console window is not opened at all.

有没有一种方法,使可通过一个单元测试来进行交互控制台窗口?

Is there a way to make the Console window available to be interacted via a unit test?

谢谢!

推荐答案

注:下面原来的答案应该向上穿过VS2012为VS的任何版本。 VS2013似乎并不有一个测试结果窗口了。相反,如果你需要特定的测试输出可以使用@ Trace.Write()写输出,写入到输出窗口。

NOTE: The original answer below should work for any version of VS up through VS2012. VS2013 does not appear to have a Test Results window anymore. Instead, if you need test-specific output you can use @Stretch's suggestion of Trace.Write() to write output to write to the Output window.

Console.Write 方法不写控制台 - 写入到任何被挂接到的正在运行的进程的标准输出句柄。同样, Console.Read 读取无论是挂在标准输入输入。

The Console.Write method does not write to the "console" -- it writes to whatever is hooked up to the standard output handle for the running process. Similarly, Console.Read reads input from whatever is hooked up to the standard input.

当你运行一个单位通过VS2010的测试,标准输出是由测试工具重定向和测试输出的一部分存储。您可以通过右键点击测试结果窗口,并添加一个名为输出(stdout),以显示中的列看到这一点。这将显示已写入到标准输出任何东西。

When you run a unit test through VS2010, standard output is redirected by the test harness and stored as part of the test output. You can see this by right-clicking the Test Results window and adding the column named "Output (StdOut)" to the display. This will show anything that was written to stdout.

您的可能的手动打开控制台窗口,使用P / Invoke为@ sinni800说。从阅读 AllocConsole 文件,看来该功能将重置标准输入标准输出把手指向新的控制台窗口。 (我不是100%肯定有关,这似乎有点错误的我,如果我已经重定向标准输出适用于Windows,从我偷的,但我没有。试过)

You could manually open a console window, using P/Invoke as @sinni800 says. From reading the AllocConsole documentation, it appears that the function will reset stdin and stdout handles to point to the new console window. (I'm not 100% sure about that; it seems kinda wrong to me if I've already redirected stdout for Windows to steal it from me, but I haven't tried.)

在一般情况下,虽然,我认为这是一个坏主意;如果你想要使用控制台是转储你的单元测试的更多信息,输出是有你。继续使用 Console.WriteLine 你的方式,并为您在当它这样做的测试结果窗口中显示输出结果。

In general, though, I think it's a bad idea; if all you want to use the console for is to dump more information about your unit test, the output is there for you. Keep using Console.WriteLine the way you are, and check the output results in the Test Results window when it's done.

这篇关于我可以写入控制台单元测试?如果是的话,为什么不打开控制台窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆