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.
PHPUnit provides methods that are used to automatically create objects that will replace the original object in our test. createMock($type) and getMockBuilder($type) methods are used to create mock object. The createMock method immediately returns a mock object of the specified type.
Stub. Stubs are used with query like methods - methods that return things, but it's not important if they're actually called. $stub = $this->createMock(SomeClass::class); $stub->method('getSomething') ->willReturn('foo'); $sut->action($stub);
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
If you have classes with magic methods you can use:
$mock->method('__get')->with('property')->willReturn('value');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With