我正在使用 PHPUnit 测试 Symfony2 项目中使用的类的私有(private)方法。 我正在使用许多开发人员描述的私有(private)方法测试策略(通过反射),例如 http://aaronsaray.com/blog/2011/08/16/testing-protected-and-private-attributes-and-methods-using-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()));
}
}
为什么?
提前谢谢你
最佳答案
创建反射方法时需要使用整个命名空间类名,即使包含 use
语句。
new \ReflectionClass('My\CalendarBundle\Calendar\Calendar');
这是因为你将类名作为字符串传递给构造函数,所以它不知道你的 use
语句,而是在全局命名空间中寻找类名。
另外,对于它的值(value),您实际上不需要创建 ReflectionClass
,然后在其上调用 getMethod()
。相反,您可以直接创建一个 ReflectionMethod
对象。
new \ReflectionMethod('My\CalendarBundle\Calendar\Calendar', 'calculateDaysPreviousMonth');
应该基本相同,但要短一些。
关于reflection - 在 PHPUnit 中使用反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12919640/