问题描述
如何创建一个扩展PHPUnit_Framework_TestCase的基类,并将其用于子类化实际的测试用例,而无需由PHPUnit测试基类本身?
How can I create a base class that extends PHPUnit_Framework_TestCase and use that for subclassing actual test cases, without having the base class itself tested by PHPUnit?
我有一系列相关的测试用例,为此我创建了一个基类,该基类包含一些将由所有测试用例继承的通用测试:
I have a series of related test cases for which I have created a base class that contains some common tests to be inherited by all test cases:
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
}
}
我的问题是,当我尝试运行文件夹中的所有测试时,它失败了(没有输出).
My problem is that when I try to run all the tests in the folder, it fails (without output).
尝试调试我发现问题出在基类本身就是PHPUnit_Framework_TestCase的子类,因此PHPUnit也将尝试运行其测试. (直到那时,我天真地认为只有实际测试文件中定义的类(即以Test.php结尾的文件名)才可以被测试.)
Trying to debug I've found that the problem lies with the base class being itself a subclass of PHPUnit_Framework_TestCase and therefore PHPUnit will also try to run its tests. (Until then I naively thought that only classes defined inside actual test files - filenames ending in Test.php - would be tested.)
由于特定实现中的细节,无法在上下文中将基类作为测试用例运行.
Running the base class as a test case out of context doesn't work due to details in my specific implementation.
如何避免测试基类,而仅测试派生类?
How can I avoid the base class being tested, and only test the derived classes?
推荐答案
将其抽象化,PHPUnit应该忽略它.
Make it abstract, PHPUnit should ignore it.
这篇关于扩展PHPUnit_Framework_TestCase的不可测试基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!