不可扩展的基本类,扩展PHPUnit_Framework_TestCase

问题描述 投票:26回答:2

摘要

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

由于我的特定实现中的细节,无法在上下文中将基类作为测试用例运行。

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

php unit-testing phpunit subclassing base-class
2个回答
36
投票

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.