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 mock a method with different arguments in PHPUnit?
- How to run tests in parallel with PHPUnit?
- How to run all PHPUnit tests?
- How to run only certain methods in PHPUnit?
- How to mock a static method with PHPUnit?
- How to mock a query builder with PHPUnit?
- How to launch one test with PHPUnit?
- How to check if a JSON contains a value in PHPUnit?
- How to use hooks in PHPUnit?
See more codes...