phpunitHow to mock a property in PHPUnit?
Mocking a property in PHPUnit can be done using the setProperty method of the PHPUnit_Framework_TestCase class.
$mock = $this->getMockBuilder('MyClass')
->setMethods(array('myMethod'))
->getMock();
$mock->expects($this->any())
->method('myMethod')
->will($this->returnValue('foo'));
$this->setProperty($mock, 'myProperty', 'bar');
The code above will set the myProperty property of the MyClass mock object to bar.
Code explanation
$mock = $this->getMockBuilder('MyClass')- creates a mock object of theMyClassclass.->setMethods(array('myMethod'))- sets the methods to be mocked.->getMock();- returns the mock object.$mock->expects($this->any())- sets the expectation for themyMethodmethod.->method('myMethod')- specifies the method to be mocked.->will($this->returnValue('foo'));- sets the return value for themyMethodmethod.$this->setProperty($mock, 'myProperty', 'bar');- sets themyPropertyproperty of theMyClassmock object tobar.
Output example
No output.
Helpful links
More of Phpunit
- How to stop PHPUnit on failure?
- How to show warnings in PHPUnit?
- How to run tests in parallel with PHPUnit?
- How to skip a PHPUnit test?
- How to order tests with PHPUnit?
- How to mock a method with different arguments in PHPUnit?
- What are PHPUnit required extensions
- How to install PHPUnit with a PHAR file?
- How to use named arguments in PHPUnit?
- How to log with PHPUnit?
See more codes...