G
G
ganjo8882019-04-25 20:27:12
PHP
ganjo888, 2019-04-25 20:27:12

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)
    {
  
    }
}

Tried like this
$class = new ReflectionClass(AbstractClass::class);
$method = $class->getMethod('request');
$method->setAccessible(true);
$document = new Document();
$result =  $method->invoke($document,$params);

I get
TypeError: Argument 2 passed to Illuminate\Log\LogManager::info() must be of the type array, object given, c

Answer the question

In order to leave comments, you need to log in

2 answer(s)
U
user49981, 2019-04-26
@ganjo888

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);
    }
}

K
Kirill Nesmeyanov, 2019-04-25
@SerafimArts

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 question

Ask a Question

731 491 924 answers to any question