问题描述
当你使用合成时,你可以模拟你的测试类所依赖的其他对象
,但是当你使用
继承时,你不能模拟基类。 (或者你可以吗?)
When you use composition, then you can mock the other objectsfrom which your class-under-test depends, but when you useinheritance, you can't mock the base class. (Or can you?)
我通常会尝试,
但有时继承似乎是最好的工具
- 至少在单元测试之前。
I generally try to prefer composition over inheritance,but sometimes inheritance really seems like the best toolfor the job - well, at least until it comes to unit-testing.
那么,你如何测试继承?或者你只是将它丢弃为
untestable并使用组合代替?
So, how do you test inheritance? Or do you just trash it asuntestable and use composition instead?
注意:我主要使用PHP和PHPUnit,所以帮助在那一边
非常感谢。但是如果在其他语言中有解决这个问题的方法,知道
也会很有趣。
Note: I mostly use PHP and PHPUnit, so help on that sideis most appreciated. But it would also be interesting to knowif there are solutions to this problem in other languages.
推荐答案
使用反映类层次结构的单元测试套件。如果你有一个基类Base和派生类Derived,那么就有测试类BaseTests并从DerivedTests派生。 BaseTests负责测试Base中定义的所有内容。 DerivedTests继承了这些测试,并且还负责测试Derived中的所有内容。
Use a suite of unit tests that mirrors the class hierarchy. If you have a base class Base and a derived class Derived, then have test classes BaseTests and derived from that DerivedTests. BaseTests is responsible for testing everything defined in Base. DerivedTests inherits those tests and is also responsible for testing everything in Derived.
如果要在Base中测试受保护的虚拟方法(即Base与其后代类之间的接口) )创建一个测试该接口的仅测试派生类也是有意义的。
If you want to test the protected virtual methods in Base (i.e. the interface between Base and its descendent classes) it may also make sense to make a test-only derived class that tests that interface.
这篇关于如何对继承对象进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!