扩展 PHPUnit_Framework_TestCase 的不可测试基类

Posted

技术标签:

【中文标题】扩展 PHPUnit_Framework_TestCase 的不可测试基类【英文标题】:Non-testable base class extending PHPUnit_Framework_TestCase 【发布时间】:2012-03-14 08:46:02 【问题描述】:

总结

如何创建一个扩展 phpUnit_Framework_TestCase 的基类并将其用于子类化实际测试用例,而不需要 PHPUnit 对基类本身进行测试?

进一步说明

我有一系列相关的测试用例,为此我创建了一个基类,其中包含一些要被所有测试用例继承的通用测试:

BaseClass_TestCase.php:
class BaseClass_TestCase extends PHPUnit_Framework_TestCase  
  function test_common() 
    // Test that should be run for all derived test cases
  


MyTestCase1Test.php:
include 'BaseClass_TestCase.php';
class MyTestCase1 extends BaseClass_TestCase 
    function setUp() 
      // Setting up
    
    function test_this() 
      // Test particular to MyTestCase1
    


MyTestCase2Test.php:
include 'BaseClass_TestCase.php';
class MyTestCase2 extends BaseClass_TestCase 
    function setUp() 
      // Setting up
    
    function test_this() 
      // Test particular to MyTestCase2
    

我的问题是,当我尝试运行文件夹中的所有测试时,它失败了(没有输出)。

尝试调试我发现问题在于基类本身是 PHPUnit_Framework_TestCase 的子类,因此 PHPUnit 也会尝试运行其测试。 (在那之前,我天真地认为只有在实际测试文件中定义的类 - 以 Test.php 结尾的文件名 - 才会被测试。)

由于我的具体实现中的细节,将基类作为测试用例脱离上下文运行是行不通的。

如何避免基类被测试,只测试派生类?

【问题讨论】:

对于遇到类似问题的每个人 - 请查看此帖子,因为它可能对您有所帮助:***.com/a/20074589/4483415 【参考方案1】:

为避免任何文件被测试,您可以将其排除在phpunit.xml 文件中。你的情况是<exclude>./tests/BaseClass_TestCase.php</exclude> Whole file example

【讨论】:

【参考方案2】:

让它抽象,PHPUnit 应该忽略它。

【讨论】:

我的问题是我使用的是 Yii 框架,而 Yii 类自动加载器似乎无法识别抽象类。我收到错误Class 'unit/MasterDataValidatorTest' could not be found in '<project>/protected/tests/unit/MasterDataValidatorTest.php'.。你也知道解决方案吗? :-) 不能用 final 代替吗? @Maximum86 你试过了吗?我没有。最终类仍然可以被实例化,所以我猜 PHPUnit 会认为它是一个测试类。

以上是关于扩展 PHPUnit_Framework_TestCase 的不可测试基类的主要内容,如果未能解决你的问题,请参考以下文章