模拟“System.Console"行为 [英] Mocking 'System.Console' behaviour

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

问题描述

是否有通过针对接口而不是 System.Console 进行编程来使 C# 控制台应用程序可进行单元测试的标准方法?

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?

推荐答案

我认为您使用界面的方法会奏效,但我认为我不会使用事件.假设应用程序不接受命令行参数以外的用户输入,我可能会使用这样的东西来包装 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 将所有写入存储到一个缓冲区中,然后我可以对其进行断言,或者我将创建一个模拟并验证 WriteWriteLine 使用我预期的参数调用.如果您的应用程序要对控制台进行大量写入(比如 +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.另一个问题是 WriteWriteLine 方法有 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.

就我个人而言,我认为我会采用 SetOut 方法.这只是您必须在单元测试开始时添加的一行(或可能在 SetUp 方法中),您可以对写入 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天全站免登陆