user3342730
user3342730

Reputation: 7

How to get private property from phpUnit Mock object

For example I have class

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

After I do mock object

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

So now I wanna get private property color of Car class

How to do it?!

I can do public method like getCar and it will work, but I wanna look for another way.

I tried use ReflectionClass for it but it was wrong.

Upvotes: 0

Views: 3687

Answers (1)

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);
}   

Upvotes: 1

Related Questions