如何通过反射获得模拟特征的私有财产



Trait看起来像这样:

trait A{
    private $model;
    public function __construct($model){
        $this->model = $model;
        $this->methodToStub();    
    }
...
}

当我尝试在单元测试中通过反射获得模拟特征的属性$model:

$mock = $this->getMockForTrait(A::class,[],'MockedTrait', false, true, true, ['methodToStub']);
$mock->expects($this->exactly(1))->method('methodToStub');
$mock->__construct('model');
$reflection = new ReflectionClass(A::class);
$property = $reflection->getProperty('model');
$property->setAccessible(true);
$value = $property->getValue($mock);

我收到此错误:

未定义的属性:模拟特征::$model

任何想法,为什么?

我看到的问题是你试图使用 A 特征的反射来访问 MockedTrait::$model 的值。但可能 MockedTrait::$model 的"签名"与 A::$model 的"签名"不同。

由于 Mock 对象类是在 phpunit 中使用 eval 声明的,因此可以访问 MockedTrait 类,您可以尝试如下操作:

$reflection = new ReflectionClass(MockedTrait::class);

这应该有效(可能(。