如何使内部/助手功能可测试? [英] How to make internal/helper functions testable?
问题描述
假设我有一些函数Foo
,它使用两个内部帮助器函数bar
和baz
.
Suppose that I have some function Foo
that uses two internal helper functions bar
and baz
.
是否有一种组织代码的方式,使得bar
和baz
保持看不见",但同时可以进行单元测试? (最好是bar
和baz
的单元测试与主要功能Foo
的单元测试在同一个套件中.)
Is there a way to organize the code so that bar
and baz
remain "out of sight", but at the same time can be unit-tested? (Preferably, the unit tests for bar
and baz
would be in the same suite as the unit tests for the main function Foo
.)
推荐答案
有一些实现此目的的选项.
There are a few options to achieve this.
首先,Foo
是否需要是一个函数?如果它是一个类,则可以将bar
和baz
分别实现为Hidden
和Access='protected'
,这已经非常紧密地锁定了.然后,您可以创建访问bar
和baz
进行测试的特定于测试的子类.您还可以查看访问权限测试,以根据需要进一步将其锁定在其他视图之外.
First, does Foo
need to be a function? If it is a class then you can implement bar
and baz
as Hidden
and Access='protected'
which is pretty tightly locked down. Then you can create a test specific subclass that accesses bar
and baz
for testing. You can also scope the access to the test to further lock it from others view if desired.
如果您确实希望Foo
是一个函数,那么您仍然可以选择.其中之一就是以某种方式获得测试专用局部函数的函数句柄.您可以通过Foo的一些特殊调用语法来执行此操作,该语法在被调用时会将这些函数返回给测试.但是,这以一种可能引起混淆的方式修改了生产代码,并且实质上将测试逻辑插入了生产中.我更喜欢通过将这些函数放入程序包中来隐藏它们,以便它们不在全局名称空间中.程序包的名称可以表明它们已超出限制,不是您支持的界面的一部分.
If you do want Foo
to be a function then you still have options. One of those is to somehow get a function handle to the private local functions to your tests. You can do this through some special calling syntax of Foo that returns these functions to a test when called. This however, modifies the production code in a potentially confusing way, and it essentially inserts test logic into production. I would prefer hiding these functions by putting them into a package so that they are not in the global namespace. The name of the package can indicate that they are off limits and not part of your supported interface.
最后,一种选择是简单地使用公共接口来测试这些功能.显然,在某些情况下会从函数中调用它们.您可能需要考虑通过界面的前门编写测试.这样做的好处之一是,您无需更改测试就可以轻松更改本地函数结构的实现.私有函数是私有的,因为根据定义,它们是实现的一部分,而不是接口的一部分.如果您发现它足够复杂,需要独立于Foo
的接口进行自己的测试,则可能应该将其分解为如上所述的另一个包函数或类,以便对其进行单元测试.
Finally, one option is to simply use the public interface in order to test these functions. Clearly they are called from the function in some scenario. You may want to consider writing a test through the front door of your interface. One benefit of this is that you would then be able to change the implementation of your local function structure easily without modifying your test. The private functions are private because by definition they are part of your implementation, not your interface. If you find it complex enough to require its own test independent from the interface of Foo
then it should probably just be broken out into another package function or class as described above in order to unit test it.
这篇关于如何使内部/助手功能可测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!