我可以在单元测试中写入控制台吗?如果是,为什么控制台窗口没有打开? [英] Can I write into console in a unit test? If yes, why doesn't the console window open?

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

问题描述

我在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似乎不再具有测试结果"窗口.相反,如果您需要特定于测试的输出,则可以使用@Stretch的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 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)"的列来查看.这将显示任何写入到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.

可以使用@ sinni800所说的P/Invoke手动打开控制台窗口.通过阅读AllocConsole文档,似乎该函数将重置stdinstdout句柄以指向新的控制台窗口. (我对此不是100%的确定;如果我已经重定向Windows的stdout来从我那里窃取它,但我没有尝试过,这对我来说似乎是错误的.)

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天全站免登陆