静态方法和单元测试 [英] static methods and unit tests
问题描述
我一直在读,静态方法往往避免使用TDD时,因为他们往往很难模拟。我发现,单元测试最简单的事情是一个静态方法,具有简单的功能。不需要实例化任何类,鼓励方法,一个简单的,做一件事,是独立的等。
I've been reading that static methods tend to be avoided when using TDD because they tend to be hard to mock. I find though, that the easiest thing to unit test is a static method that has simple functionality. Don't have to instantiate any classes, encourages methods that a simple, do one thing, are "standalone" etc.
有人可以解释TDD最佳实践之间的差异,务实轻松?
Can someone explain this discrepancy between TDD best practices and pragmatic ease?
感谢,
A
thanks, A
推荐答案
静态方法很容易测试,但直接调用静态方法的东西通常不容易独立于它依赖的静态方法进行测试。使用非静态方法,您可以使用stub / mock / fake实例来简化测试,但是如果您测试的代码调用静态方法,它将有效地硬连线到该静态方法。
A static method is easy to test, but something that directly calls a static method generally is not easy to test independent of the static method it depends on. With a non-static method you can use a stub/mock/fake instance to ease testing, but if the code you're testing calls static methods it's effectively "hard-wired" to that static method.
这篇关于静态方法和单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!