PHPUnit Mock an object's properties

Riccardo Cedrola picture Riccardo Cedrola · Jun 15, 2017 · Viewed 25k times · Source

I'm looking for a way to mock an object and populate its properties. Here's an example of a method who uses a property of another object:

class MyClass {

    private $_object;

    public function methodUnderTest($object) {
        $this->_object = $object;
        return $this->_object->property
    }
}

To Unit Test this method I should create a mock of $object with the getMockBuilder() method from PHPUnit. But I can't find a way to mock the properties of the $object, just the methods.

Answer

Riccardo Cedrola picture Riccardo Cedrola · Jun 16, 2017

To add properties to a mocked object, you just set them as you'd normally do with an object:

$mock = $this->getMockBuilder('MyClass')
             ->disableOriginalConstructor()
             ->getMock();

$mock->property = 'some_value';

$mock->property will now return 'some_value'

Thanks to akond

P.s. for my project, this doesn't work with some classes, and when I try to call $mock->property it just returns NULL