phpunitHow to test an abstract class with PHPUnit?
Abstract classes can be tested with PHPUnit by creating a concrete subclass of the abstract class and then testing the subclass.
<?php
abstract class AbstractClass
{
abstract protected function getValue();
abstract protected function prefixValue($prefix);
public function printOut()
{
print $this->getValue() . "\n";
}
}
class ConcreteClass extends AbstractClass
{
protected function getValue()
{
return "ConcreteClass";
}
public function prefixValue($prefix)
{
return "{$prefix}ConcreteClass";
}
}
class AbstractClassTest extends PHPUnit_Framework_TestCase
{
public function testGetValue()
{
$class = new ConcreteClass;
$this->assertEquals('ConcreteClass', $class->getValue());
}
public function testPrefixValue()
{
$class = new ConcreteClass;
$this->assertEquals('prefixedConcreteClass', $class->prefixValue('prefixed'));
}
}
Output example
PHPUnit 5.7.21 by Sebastian Bergmann and contributors.
.. 2 / 2 (100%)
Time: 5 ms, Memory: 4.00MB
OK (2 tests, 2 assertions)
Code explanation
abstract class AbstractClass
: This is the abstract class that will be tested.class ConcreteClass extends AbstractClass
: This is the concrete subclass of the abstract class that will be tested.class AbstractClassTest extends PHPUnit_Framework_TestCase
: This is the test class that will be used to test the abstract class.public function testGetValue()
: This is a test method that tests thegetValue()
method of the abstract class.public function testPrefixValue()
: This is a test method that tests theprefixValue()
method of the abstract class.
Helpful links
More of Phpunit
- How to skip a PHPUnit test?
- How to show warnings in PHPUnit?
- How to mock a method with different arguments in PHPUnit?
- What are PHPUnit required extensions
- How to run PHPUnit in quiet mode?
- How to run tests in parallel with PHPUnit?
- How to mock a property in PHPUnit?
- How to mock a static method with PHPUnit?
- How to check if a JSON contains a value in PHPUnit?
- How to mock a query builder with PHPUnit?
See more codes...