27

Summary

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?

Further explanation

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).

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?

jgivoni
  • 1,605
  • 1
  • 15
  • 24
  • For everyone that got here with similar problem - check this post because it may help you: http://stackoverflow.com/a/20074589/4483415 – Szymon Sadło Oct 28 '16 at 10:43

2 Answers2

44

Make it abstract, PHPUnit should ignore it.

Mike B
  • 31,886
  • 13
  • 87
  • 111
  • My problem with this is that I use the Yii framework, and the Yii class autoloader does not seem to recognize abstract classes. I get the error `Class 'unit/MasterDataValidatorTest' could not be found in '/protected/tests/unit/MasterDataValidatorTest.php'.`. Do you know a solution to that as well? :-) – physicalattraction Jul 03 '15 at 08:01
  • Couldn't you use final instead? – scruffycoder86 May 16 '17 at 08:05
  • @Maximum86 Have you tried it? I haven't. A final class is still able to be instantiated so my guess would be PHPUnit would consider it a test class. – Mike B May 16 '17 at 13:36
0

For avoiding any file being tested, you can exclude it in phpunit.xml file. In your case is <exclude>./tests/BaseClass_TestCase.php</exclude> Whole file example

ioannup
  • 51
  • 1
  • 5