简体   繁体   中英

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?

You should use PHPUnit's Mock feature.

https://phpunit.de/manual/current/en/test-doubles.html

Example 9.7: Stubbing a method call to return a value from a callback

will propably be helpful, you can configure, what result your call to "count" does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM