在遵循测试驱动开发范例时,我应该不会使用静态方法和类和单例 [英] Should I never use static methods and classes and singletons when following the Test Driven Development paradigm

查看:134
本文介绍了在遵循测试驱动开发范例时,我应该不会使用静态方法和类和单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读,当您尝试在项目中实施单元测试时,静态方法,静态类和单例是恶意的。当遵循TDD范式时,我应该忘记它们是否存在,并且永远不会再使用它们,有时候可以使用它们。

I've been reading that static methods, static classes, and singletons are evil when you try to implement unit testing in your project. When following the TDD paradigm, should I just forget that they ever existed and never use them again or is it ok to use them sometimes?

推荐答案

不要说永远不会 - 静态类和方法在你的工具箱中占有一席位。

Never say never--static classes and methods have their place in your toolbox.

那就是说,如果你试图隔离和测试的类测试或SUT)取决于静态类或方法,您将无法编写将SUT与静态依赖关系隔离的测试 - 当测试代码运行时,仍将使用静态调用。有时候这是很好的,但有时你想创建一个孤立的测试,只测试SUT的逻辑,没有依赖关系(通常是通过嘲笑或类似的技术)。

That said, if the class you are trying to isolate and test (subject under test or SUT) depends on a static class or method, you will be unable to write a test that isolates the SUT from that static dependency--when your test code runs it will still use the static call. Sometimes this is fine, but sometimes you want to create an isolated test that tests ONLY the logic of your SUT with no dependencies (usually via mocking or similar techniques).

一般来说,我个人使用静态类和方法相对谨慎。​​

In general I personally use static classes and methods relatively sparingly.

由于实现了Singleton的性质,他们提出了一个类似的问题,用于隔离单元测试的SUT。此外,GOF单身概念被一定百分比的软件开发人员认为是不好的做法。我恰好同意这个观点,但对这个问题几乎没有共识。在Google上快速搜索可能会让您对GOF Singleton模式的优缺点有个不错的看法。

Due to the nature of how Singletons are implemented, they present a similar problem for isolating a SUT for unit testing. In addition, the GOF singleton concept is considered to be a bad practice by a certain percentage of software developers. I happen to agree with this sentiment, but there is hardly consensus on this subject. A quick search on google will probably give you a pretty good idea of the pros and cons of the GOF Singleton pattern.

这篇关于在遵循测试驱动开发范例时,我应该不会使用静态方法和类和单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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