在PHPUnit中使用反射

Gia*_*a78 2 reflection phpunit symfony

我正在使用PHPUnit测试Symfony2项目中使用的类的私有方法.我正在使用许多开发人员描述的私有方法测试策略(通过反射),例如http://aaronsaray.com/blog/2011/08/16/testing-protected-and-private-attributes-and-methods-using -phpunit /

但不幸的是,我收到以下错误:

有1个错误:1)我的\ CalendarBundle\Tests\Calendar\CalendarTest :: testCalculateDaysPreviousMonth ReflectionException:类日历不存在/Library/WebServer/Documents/calendar/src/My/CalendarBundle/Tests/Calendar/CalendarTest.php:47

<?php
namespace My\CalendarBundle\Tests\Calendar;

use My\CalendarBundle\Calendar\Calendar;

class CalendarTest 
{    
    //this method works fine     
    public function testGetNextYear()
    {
        $this->calendar = new Calendar('12', '2012', $this->get('translator'));        
        $result = $this->calendar->getNextYear();

        $this->assertEquals(2013, $result);
    }

    public function testCalculateDaysPreviousMonth()
    {        
        $reflectionCalendar = new \ReflectionClass('Calendar'); //this is the line

        $method = $reflectionCalendar->getMethod('calculateDaysPreviousMonth');      
        $method->setAccessible(true);

        $this->assertEquals(5, $method->invokeArgs($this->calendar, array()));                 
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么?

先感谢您

the*_*ler 8

在创建反射方法时,您需要使用整个命名空间的类名,即使您包含use语句也是如此.

new \ReflectionClass('My\CalendarBundle\Calendar\Calendar');
Run Code Online (Sandbox Code Playgroud)

这是因为您将类名作为字符串传递给构造函数,因此它不知道您的use语句并且正在全局命名空间中查找类名.

而且,对于它的价值,你实际上并不需要创建一个ReflectionClass,然后调用getMethod()它.相反,您可以直接创建ReflectionMethod对象.

new \ReflectionMethod('My\CalendarBundle\Calendar\Calendar', 'calculateDaysPreviousMonth');
Run Code Online (Sandbox Code Playgroud)

这应该基本相同,但有点短.