3

Symfony2 プロジェクトで使用されているクラスのプライベート メソッドを PHPUnit でテストしています。私はhttp://aaronsaray.com/blog/2011/08/16/testing-protected-and-private-attributes-and-methods-usingなどの多くの開発者によって説明されている (リフレクションによる) プライベート メソッド テスト戦略を使用しています。 -phpunit/

しかし、残念ながら、次のエラーが発生しました。

1 つのエラーがありました: 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()));                 
    }
}

なんで?

前もって感謝します

4

1 に答える 1

9

useリフレクション メソッドを作成するときは、ステートメントを含める場合でも、名前空間クラス名全体を使用する必要があります。

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

これは、クラス名を文字列としてコンストラクターに渡しているためです。そのため、コンストラクターはuseステートメントを認識せず、グローバル名前空間でクラス名を探しています。

また、価値のあることとして、実際に を作成してReflectionClass呼び出す必要はありませんgetMethod()。代わりに、オブジェクトを直接作成できReflectionMethodます。

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

それは本質的に同じはずですが、少し短くなります。

于 2012-10-16T16:54:48.110 に答える