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.

我通常尝试更喜欢组合而不是继承,但有时候继承似乎是最好的工具 - 好吧,至少在单元测试之前。

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

那么,你如何测试继承?或者你只是把它作为不可测试而废弃并使用构图代替?

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.

注意:我主要使用PHP和PHPUnit,因此非常感谢帮助。但是知道在其他语言中是否存在解决这个问题的方法也很有趣。

5 个解决方案

#1


5

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和派生类Derived,那么就有测试类BaseTests并从DerivedTests派生。 BaseTests负责测试Base中定义的所有内容。 DerivedTests继承了这些测试,并且还负责测试Derived中的所有内容。

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.

如果要在Base中测试受保护的虚拟方法(即Base与其后代类之间的接口),那么创建一个测试该接口的仅测试派生类也是有意义的。

更多相关文章

  1. 2016.5.27 php测试中敏感度高,怎么调整
  2. PHP实现接口方法时出现致命错误
  3. PHP 导出 万级别数据 时间测试
  4. 支付宝手机接口,服务端PHP验证失败,求助
  5. 如何在进行单元测试时覆盖php://输入
  6. 在单个测试中断言多个条件,还是分成多个测试? [重复]
  7. php面向对象之抽象类和接口理解
  8. python django 基本测试 及调试 201812
  9. 如何使用phpunit测试用例测试ajax调用?

随机推荐

  1. mybatis框架的进一步封装
  2. 每个派生表必须有自己的别名(sql&php)[重复]
  3. python使用MySQLdb模块连接MySQL
  4. 更改SQLServer实例默认字符集
  5. 如何从sql server上的一个表中删除8500,0
  6. Mysql 范式、索引、视图、事务、sp等概
  7. LINQ之开放式并发控制和事务
  8. MySQL查询过程中出现lost connection to
  9. 求指导,PB12.0 如何用ini文件 连接sql 200
  10. MySQL Cluster在线添加数据节点