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

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

问题描述

我在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, the test passes, but the console window is not opened at all.

是否有一种方法可以使控制台窗口可通过单元测试进行交互?

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

推荐答案

注意:以下原始答案适用于从Visual Studio 2012到Visual Studio的任何版本.VisualStudio 2013似乎没有测试结果"窗口更多的.相反,如果您需要特定于测试的输出,则可以使用@Stretch的Trace.Write()建议将输出写入输出"窗口.

NOTE: The original answer below should work for any version of Visual Studio up through Visual Studio 2012. Visual Studio 2013 does not appear to have a Test Results window any more. 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"目录. -它写入正在连接到正在运行的进程的标准输出句柄的任何内容.同样,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.

当您通过Visual Studio 2010运行单元测试时,标准线束将由测试线束重定向并存储为测试输出的一部分.您可以通过右键单击测试结果"窗口并添加名为"Output(StdOut)"的列来查看此情况.到显示器.这将显示写入标准输出的所有内容.

When you run a unit test through Visual Studio 2010, 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 standard output.

可以使用 P/调用手动打开控制台窗口 a>为

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