Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test methods of Abstract Class with PHPUnit

Tags:

phpunit

I have an abstract class that has common methods in it, that I wish to test, so I do not have to keep testing them in each 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 the basic test case then that will test the constructor, and the GetField and other functions, then my other test files can test the abstract functions.

I want to be able to test the const has not changed, the field throws the 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 do I create the tests since I can not create the CLASS1 object as it is an abstract class?

like image 639
Steven Scott Avatar asked Mar 29 '12 18:03

Steven Scott


1 Answers

One option is to create a

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

and use that class for your tests.

The other option is to do pretty much the same but use an API phpunit provides you with:

For this see the sample Example 10.13: Testing the concrete methods of an abstract class of the phpunit documentation:

A simpler 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());
    }
}
like image 175
edorian Avatar answered Oct 22 '22 01:10

edorian