单元测试:日志记录和依赖注入 [英] Unit Testing: Logging and Dependency Injection

查看:148
本文介绍了单元测试:日志记录和依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,关于从SO和Internet上其他站点进行日志记录的最佳响应似乎是:

So regards logging from SO and other sites on the Internet the best response seems to be:

void DoSomething() {
    Logger.Log("Doing something!");
    // Code...
}

现在通常您应该避免使用静态方法,但是在记录日志(特殊情况)的情况下,这是最简单,最干净的方法.在静态类中,您可以轻松地通过配置文件/框架注入实例,以提供与DI相同的效果.

Now generally you'd avoid static methods but in the case of logging (a special case) this is the easiest and cleaniest route. Within the static class you can easily inject an instance via a config file/framework to give you the same effect as DI.

我的问题来自单元测试.

My problem comes from a unit testing perspective.

在上面的示例代码中,想象DoSomething()的重点是将两个数字加在一起.我会为此写单元测试.日志记录如何?

In the example code above imagine the point of DoSomething() was to add two numbers together. I'd write my unit tests for this fine. What about the logging?

我是否要为日志记录编写单元测试(但为记录器本身使用模拟实例)?我知道是否是这种情况,我必须编写一个集成测试来证明记录器实际上已写入日志文件,但是我不确定.

Would I write a unit test for the logging (yet use a mock instance for the logger itself)? I know if this was the case I would have to write an integration test to prove the logger actually wrote to a log file but I'm not sure.

遵循测试驱动开发(我这样做)后,我需要进行单元测试来确定接口号吗?

Following Test Driven Development (which I do) the unit test would be required for me to dictate the interface no?

有什么建议吗?

推荐答案

我个人非常虔诚地练习TDD/BDD,而且我几乎从不测试日志记录.除某些例外,日志记录是开发人员的便利性或可用性因素,不是该方法的核心规范的一部分.与该方法的实际语义相比,它的变化率也往往更高.因此,由于添加了更多的信息日志记录,您最终破坏了测试.

Personally, I practice TDD/BDD pretty religiously and I almost never test logging. With some exceptions logging is either a developer convenience or a usability factor, not part of the method's core specification. It also tends to have a MUCH higher rate of change than the actual semantics of the method, so you wind up breaking tests just because you added some more informational logging.

进行一些简单的测试日志子系统的测试可能是值得的,但是对于大多数应用程序,我不会测试每个类是否以特定方式使用日志.

It's probably worthwhile to have some tests that simply exercise the logging subsystem, but for most apps I wouldn't test that each class uses the log in a particular way.

这篇关于单元测试:日志记录和依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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