Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit Mock an object's properties

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.

like image 975
Riccardo Cedrola Avatar asked Jun 15 '17 15:06

Riccardo Cedrola


People also ask

How to Mock method in PHPUnit?

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.

What is stub in PHPUnit?

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


2 Answers

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

like image 112
Riccardo Cedrola Avatar answered Sep 21 '22 15:09

Riccardo Cedrola


If you have classes with magic methods you can use:

$mock->method('__get')->with('property')->willReturn('value'); 
like image 32
Jsowa Avatar answered Sep 17 '22 15:09

Jsowa