Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using reflection in PHPUnit

I'm testing a private method of a class used in Symfony2 project with PHPUnit. I'm using the private methods testing strategy (through reflection) described by many developers such as http://aaronsaray.com/blog/2011/08/16/testing-protected-and-private-attributes-and-methods-using-phpunit/

But unfortunately, I got the following error:

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()));                 
    }
}

Why?

Thank you in advance

like image 526
Gianluca78 Avatar asked Apr 10 '26 08:04

Gianluca78


1 Answers

You need to use the whole namespaced class name when creating your reflection method, even if you include a use statement.

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

This is because you are passing the class name as a string to the constructor, so it doesn't know about your use statement and is looking for the class name in the global namespace.

Also, for what it's worth, you don't actually need to create a ReflectionClass, then call getMethod() on it. Rather, you can directly create a ReflectionMethod object.

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

That should be essentially the same, but a bit shorter.

like image 121
theunraveler Avatar answered Apr 14 '26 02:04

theunraveler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!