如何对继承对象进行单元测试? [英] How do I unit-test inheriting objects?

查看:156
本文介绍了如何对继承对象进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你使用合成时,你可以模拟你的测试类所依赖的其他对象
,但是当你使用
继承时,你不能模拟基类。 (或者你可以吗?)

When you use composition, then you can mock the other objects from which your class-under-test depends, but when you use inheritance, 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 tool for the job - well, at least until it comes to unit-testing.

那么,你如何测试继承?或者你只是将它丢弃为
untestable并使用组合代替?

So, how do you test inheritance? Or do you just trash it as untestable and use composition instead?

注意:我主要使用PHP和PHPUnit,所以帮助在那一边
非常感谢。但是如果在其他语言中有解决这个问题的方法,知道
也会很有趣。

Note: I mostly use PHP and PHPUnit, so help on that side is most appreciated. But it would also be interesting to know if 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.

这篇关于如何对继承对象进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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