Answer the question
In order to leave comments, you need to log in
How to test a protected method of an abstract class?
class Document extends AbstractClass
{
public function handle($params)
{
$requestBody = 'body';
return $this->request($requestBody);
}
}
abstract class AbstractClass
{
protected function request($body)
{
}
}
$class = new ReflectionClass(AbstractClass::class);
$method = $class->getMethod('request');
$method->setAccessible(true);
$document = new Document();
$result = $method->invoke($document,$params);
Answer the question
In order to leave comments, you need to log in
abstract class AbstractClass
{
protected function request($body)
{
return Document::TEST_VALUE;
}
}
class Document extends AbstractClass
{
const TEST_VALUE = 403;
public function handle($params)
{
$requestBody = 'body';
return $this->request($requestBody);
}
}
class DocumentTest
{
public function testRequest()
{
$doc = new Document();
$result = $this->invokeMethod($doc, 'request', [1]);
self::assertEquals(Document::TEST_VALUE, $result);
}
private function invokeMethod(&$object, $methodName, array $parameters = array())
{
$reflection = new \ReflectionClass(get_class($object));
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invokeArgs($object, $parameters);
}
}
Protected methods are not part of the public interface, which means that testing them is not implied. Just like abstract classes are not independent entities. Yourself is more expensive.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question