惩戒“System.Console行为 [英] Mocking 'System.Console' behaviour

查看:131
本文介绍了惩戒“System.Console行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有做一个C#控制台应用程序的单元测试的通过编程对一个接口,而不是System.Console的标准方式?

Is there a standard way of making a C# console application unit-testable by programming against an interface, rather than System.Console?

例如,使用IConsole接口?

For example, using an IConsole interface?

你有没有这样做,并没有使用什么样的方法?

Have you done this, and what kind of methods did you use?

你有没有公开事件当你的应用程序需要写入到标准输出?

Did you expose events for when your application needs to write to the standard output?

推荐答案

我想用一个接口的方法是有效的,而且我不'T想我会利用事件。假设应用程序不接受超过命令行参数的其他用户输入,我可能会使用这样的包装 Console.Write / Console.WriteLine

I think your approach with an interface would work, and I don't think I would make use of events. Assuming the application does not accept user input other than command line parameters, I would probably use something like this to wrap Console.Write/Console.WriteLine:

public interface IConsoleWriter
{
    void Write(string format, params object[] args);
    void WriteLine(string format, params object[] args);
}

要考,我就可以创建一个 TestConsoleWriter ,将存储所有写入到缓冲区,然后我可以断言反对,否则我就创建一个模拟并验证的WriteLine 调用了我的预期的参数。如果您的应用程序将做一吨写作到控制台(比如+100 MB左右的输出),然后用一个模拟可能会是最好性能方面的原因,但除此之外,我想说挑哪种方法你觉得会更易于使用。

To test, I would either create a TestConsoleWriter that would store all writes into a buffer that I could then assert against, or I would create a mock and verify that Write or WriteLine was called with the parameters I expected. If your application is going to be doing a ton of writing to the console (say +100 MB or so of output), then using a mock would probably be preferable for performance reasons, but otherwise I would say pick whichever method you think would be easier to work with.

这方法确实有一些限制,但是。如果你正在使用的任何程序集,你无法修改它们写入控制台,那么你就不会看到输出,因为你不能强迫这些类使用 IConsoleWriter 。另一个问题是,的WriteLine 方法,有18个左右的过载,所以你可能会被包裹的方法很多。为了解决这些限制,你可能只是想使用 Console.SetOut 方法控制台输出重定向到自己的的TextWriter 同时测试。

This approach does have a few limitations, however. If you are using any assemblies that you cannot modify and they write to the console, then you won't see that output since you can't force those classes to use your IConsoleWriter. Another problem is that the Write and WriteLine methods have 18 or so overloads, so you may be wrapping alot of methods. To get around these limitations, you may just want to use the Console.SetOut method to redirect the console output to your own TextWriter while testing.

我个人认为,我想借此放样办法。这也只是一条线,你必须在你的单元测试的开头添加(或可能在设置法),你可以直接断言反对什么被写进的TextWriter

Personally, I think I would take the SetOut approach. It would just be one line you have to add at the beginning of your unit tests (or possibly in a SetUp method) and you can just assert against what is written into the TextWriter.

这篇关于惩戒“System.Console行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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