给定对象不是 class 的实例,当尝试在 PHPUnit 测试中设置成员变量时,此方法声明错误
Given object is not an instance of the class this method was declared in error when trying to set member variable inside PHPUnit test
尝试在我的 class 上设置 "logger" 属性时出现以下错误。
ReflectionException: Given object is not an instance of the class this
method was declared in
public function testCheckForRecentActivity()
{
self::bootKernel();
$plan = new \ReflectionClass('AppBundle\Services\Courses\Revision0');
$logger = $plan->getMethod('setLogger');
$logger->setAccessible(true);
$logger->invoke($plan, static::$kernel->getContainer()->get('logger.golf'));
// ....
}
class 层次结构如下所示:
class Revision0 extends Base
abstract class Base extends Plans\PlanBase
abstract class PlanBase
使用 LoggerTrait
(use LoggerTrait;
)
LoggerTrait
看起来像:
/**
* @var LoggerInterface
*/
protected $logger;
/**
* @required
* @param LoggerInterface $logger
*/
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
我是否遗漏了什么阻止我在测试中设置记录器?
您的 ReflectionMethod->invoke()
调用中的第一个参数是错误的。它应该是 'AppBundle\Services\Courses\Revision0'
的一个实例。另见此处:https://www.php.net/manual/de/reflectionmethod.invoke.php
尝试在我的 class 上设置 "logger" 属性时出现以下错误。
ReflectionException: Given object is not an instance of the class this method was declared in
public function testCheckForRecentActivity()
{
self::bootKernel();
$plan = new \ReflectionClass('AppBundle\Services\Courses\Revision0');
$logger = $plan->getMethod('setLogger');
$logger->setAccessible(true);
$logger->invoke($plan, static::$kernel->getContainer()->get('logger.golf'));
// ....
}
class 层次结构如下所示:
class Revision0 extends Base
abstract class Base extends Plans\PlanBase
abstract class PlanBase
使用 LoggerTrait
(use LoggerTrait;
)
LoggerTrait
看起来像:
/**
* @var LoggerInterface
*/
protected $logger;
/**
* @required
* @param LoggerInterface $logger
*/
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
我是否遗漏了什么阻止我在测试中设置记录器?
您的 ReflectionMethod->invoke()
调用中的第一个参数是错误的。它应该是 'AppBundle\Services\Courses\Revision0'
的一个实例。另见此处:https://www.php.net/manual/de/reflectionmethod.invoke.php