2012-10-16 73 views
2

我正在用PHPUnit測試Symfony2項目中使用的類的私有方法。 我使用的許多開發商,如http://aaronsaray.com/blog/2011/08/16/testing-protected-and-private-attributes-and-methods-using-phpunit/在PHPUnit中使用反射

描述的私有方法的測試策略(通過反射)但不幸的是,我得到了以下錯誤:

There was 1 error: 1) My\CalendarBundle\Tests\Calendar\CalendarTest::testCalculateDaysPreviousMonth ReflectionException: Class Calendar does not exist /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()));     
    } 
} 

爲什麼?

預先感謝您

回答

8

您需要在創建反射法時,使用整個命名空間中的類名,即使你包括use聲明。

new \ReflectionClass('My\CalendarBundle\Calendar\Calendar'); 

這是因爲要傳遞的類名作爲一個字符串構造函數,所以它不知道你use聲明,並期待在全局命名空間中的類名。

此外,對於它的價值,您實際上並不需要創建ReflectionClass,然後致電getMethod()就可以了。相反,您可以直接創建ReflectionMethod對象。

new \ReflectionMethod('My\CalendarBundle\Calendar\Calendar', 'calculateDaysPreviousMonth'); 

這應該是基本相同,但有點短。

+1

非常感謝!我在單元測試方面很新,每一個建議都很寶貴! :) – Gianluca78