扩展PHPUnit_Framework_TestCase的不可测试的基类

时间:2012-02-23 21:29:23

标签: php unit-testing phpunit subclassing base-class

摘要

如何创建扩展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结尾的文件名 - 才会被测试。)

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

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

2 个答案:

答案 0 :(得分:35)

将其抽象化,PHPUnit应该忽略它。

答案 1 :(得分:0)

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

相关问题