本文介绍了扩展 PHPUnit_Framework_TestCase 的不可测试基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个扩展 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 的不可测试基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:07