Test methods for abstract class with PHPUnit

I have an abstract class that has generic methods that I want to test, so I don’t need to test them in every class that extends this class.

abstract class Class1 implements iClass1 { const VALUE = 'A'; private $Return; public function __construct($Field = NULL) { if( ! is_null($Field) ) $this->SetField($Field); } public function GetField() { return $this->Return; } public function SetField($Field) { if (strlen($Field) != 3) throw new CLASS1_EXCEPTION('Field "' . $Field . '" must be 3 digits.'); $this->Return = $FieldCode; } abstract function CalculateData(); } 

I want to create a basic test case that will check the constructor, and GetField, and other functions, then my other test files can test abstract functions.

I want to be able to verify that the constant has not changed, the field throws an exception, etc.

TEST:

 class TEST_CLASS1 extends PHPUnit_Framework_TestCase { protected function setUp() { require_once('CLASS1.php'); } public function testConstants() { $this->assertEquals(CLASS1, 'A'); } /* @expectedException CLASS1_EXCEPTION public function testLargeFieldException() { $class1 = new CLASS1('ABCD'); $class1 = new CLASS1(); $class1->SetField('ABCD'); } } 

How to create tests, since I cannot create a CLASS1 object, since it is an abstract class?

+7
source share
1 answer

One option is to create

 TestableClass1 extends Class1 { public function CalculateData() {} } 

and use this class for your tests.

Another option is to do almost the same, but using the phpunit API provides you with:

For this, see sample Example 10.13: Testing specific methods of the abstract class phpunit documentation :

The simplest example:

 abstract class AbstractClass { public function concreteMethod() { return 5; } public abstract function abstractMethod(); } class AbstractClassTest extends PHPUnit_Framework_TestCase { public function testConcreteMethod() { $sut = $this->getMockForAbstractClass('AbstractClass'); $this->assertSame(5, $sut->concreteMethod()); } } 
+19
source

All Articles