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 theMyClass
class.->setMethods(array('myMethod'))
- sets the methods to be mocked.->getMock();
- returns the mock object.$mock->expects($this->any())
- sets the expectation for themyMethod
method.->method('myMethod')
- specifies the method to be mocked.->will($this->returnValue('foo'));
- sets the return value for themyMethod
method.$this->setProperty($mock, 'myProperty', 'bar');
- sets themyProperty
property of theMyClass
mock object tobar
.
Output example
No output.
Helpful links
More of Phpunit
- How to skip a PHPUnit test?
- How to run PHPUnit in quiet mode?
- How to run tests in parallel with PHPUnit?
- How to mock a static method with PHPUnit?
- How to show warnings in PHPUnit?
- How to run all PHPUnit tests?
- How to install PHPUnit with a PHAR file?
- How to mock a method with different arguments in PHPUnit?
- How to increase memory limit in PHPUnit?
See more codes...