reflection - 在 PHPUnit 中使用反射

标签 reflection symfony phpunit

我正在使用 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/

相关文章:

java - 如何在java中使用反射扩展基类的多个类

java - 调用具有未知参数的构造函数

symfony - Doctrine Query Builder, "between"表达式和子查询

php - 为什么我会收到错误 Failed asserting that Response Object (...) is an instance of class "RedirectResponse"?

php - mock :模拟 publicaly 重写 protected 方法

批处理文件中的 PHPUnit 设置

java - 在运行时确定泛型方法参数的类型

java - 使用反射 api 时抛出 NoSuchMethodException

session - 从另一个 php 文件访问 Symfony2 session ?

Symfony twig 如何将类添加到表单行