dsfbnhc4373 2016-06-02 19:12
浏览 90

PHP在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?

  • 写回答

1条回答 默认 最新

  • dsyua2828 2016-06-02 19:21
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?