phpunitHow to mock a method with PHPUnit?
PHPUnit provides a mock
method to create a mock object of a class or interface. This mock object can be used to replace the actual class or interface in unit tests.
Example code
$mock = $this->getMockBuilder('MyClass')
->setMethods(array('myMethod'))
->getMock();
This code creates a mock object of the MyClass
class with the myMethod
method mocked.
Code explanation
$this->getMockBuilder('MyClass')
: creates a mock object of theMyClass
class.->setMethods(array('myMethod'))
: specifies the methods to be mocked.->getMock()
: returns the mock object.
Helpful links
More of Phpunit
- How to show warnings in PHPUnit?
- How to skip a PHPUnit test?
- How to run tests in parallel with PHPUnit?
- How to stop PHPUnit on failure?
- What are PHPUnit required extensions
- How to mock a query builder with PHPUnit?
- How to run all PHPUnit tests?
- How to install PHPUnit with a PHAR file?
- How to use named arguments in PHPUnit?
- How to mock with PHPUnit?
See more codes...