rook
rook

Reputation: 1154

How to test an abstract class?

I am confused in the way how to start testing an abstract class.

An example:

abstract class Command
{
    private $params;

    public function with(array $params = [])
    {
        $this->params = $params;
    }

    public function getParams()
    {
        return $this->params;
    }

    abstract public function run();
}

Should I test it like:

/** @test */
public function is_an_abstract_class()
{
    $command = $this->getReflectionClass();
    $this->assertTrue($command->isAbstract());
}

/** @test */
public function has_an_run_method()
{
    $command = $this->getReflectionClass();
    $method = $this->getReflectionMethod('run');

    $this->assertTrue($command->hasMethod('run'));
    $this->assertTrue($method->isAbstract());
    $this->assertTrue($method->isPublic());
    $this->assertEquals(0, $method->getNumberOfParameters());
}

Upvotes: 1

Views: 74

Answers (1)

VoiceOfUnreason
VoiceOfUnreason

Reputation: 57214

Should I not test abstract classes?

Under most circumstances, this would be my choice.

Reason #1: the fact that some class inherits from an abstract class is an implementation detail, not a behavior. We don't want to couple our tests to implementation details.

Reason #2: I would expect the code in the abstract class to be covered by the tests that cover its descendants.

If you design were emerging "test first", then you already have coverage of this code, because the abstract class would be something that you would introduce to your design via refactoring a class that was already under test.

Upvotes: 1

Related Questions