如何从phpUnit Mock对象获取私有属性

问题描述 投票:0回答:1

比如我上课了

class Car
{
   private $color='red';
}

我做模拟对象后

$carMock = $this->getMockBuilder(Car::class)->getMock();

所以现在我想获得Car class的私人财产颜色

怎么做?!

我可以做像getCar这样的公共方法,它可以工作,但我想寻找另一种方式。

我试过使用ReflectionClass,但它错了。

php phpunit
1个回答
0
投票
public function setProtectedProperty($object, $property, $value) {
    $reflection = new \ReflectionClass($object);
    $reflection_property = $reflection->getProperty($property);
    $reflection_property->setAccessible(true);
    $reflection_property->setValue($object, $value);
}

public function getProtectedProperty($object, $property) {
    $reflection = new \ReflectionClass($object);
    $reflection_property = $reflection->getProperty($property);
    $reflection_property->setAccessible(true);
    $reflection_property->getValue($object);
}   
© www.soinside.com 2019 - 2024. All rights reserved.