jeudi 2 juin 2016

PHP call a method on a ReflectionClass

I'm a novice developer trying to write a test suite for an existing Laravel app. Currently I'm trying to write tests for a controller but the authentication system used is strangely implemented and difficult to get around. I can't simply:

$user = \User::find(1);
$this->be($user);

I need to instantiate the controller and set a private property in its base class. To get around this, I'm trying to use reflection and setting the constructor properties and the user property manually. My issue arises when I try to invoke the method on the reflection object and I don't know how to get around it. My test method:

public function testCount()
{
    $user = \User::find(1);
    $this->be($user);

    $leadRepositoryInterface = m::mock('CRM\Storage\Lead\LeadRepositoryInterface');
    $response = m::mock('ColorJar\ApiResponse\Response');

    $leadsController = new ReflectionClass('LeadsController');

    $leadsControllerLead = $leadsController->getProperty('lead');
    $leadsControllerLead->setAccessible(true);
    $leadsControllerResponse = $leadsController->getProperty('response');
    $leadsControllerResponse->setAccessible(true);
    $leadsControllerCrmuser = $leadsController->getProperty('crmUser');
    $leadsControllerCrmuser->setAccessible(true);

    $leadsControllerLead->setValue($leadsController, $leadRepositoryInterface);
    $leadsControllerResponse->setValue($leadsController, $response);
    $leadsControllerCrmuser->setValue($leadsController, $user);

    $reflectionMethod = new ReflectionMethod('ReflectionClass', 'count');

    $this->assertEquals('jdsf', $reflectionMethod->invoke($leadsController));
}

generates the following error:

LeadsControllerTest::testCount
ReflectionException: Method ReflectionClass::count() does not exist

I realize that I'm calling count() on an instance of ReflectionClass instead of LeadsController but I don't know how else to set these properties, in particular the crmUser since it's a private property of the class that LeadsController inherits from. How do I make this work?





Aucun commentaire:

Enregistrer un commentaire