MacBook avec code sur un bureau

PHPUnit – Set a protected or private property on a mock

Using mocks it is often necessary to give a value to a private or protected variable. To do this, just use the Reflection class.

$basket = $this->getMockBuilder('Basket')
    ->disableOriginalConstructor()
    ->getMock();
$basketReflection = new ReflectionClass($basket);
$sessionId = $basketReflection->getProperty('sessionId');
$sessionId->setAccessible(true);
$sessionId->setValue($basket,'abc');

so the sessionId value in our Mock will be ‘abc’.