phpunitHow to mock with PHPUnit?
PHPUnit provides a powerful mocking framework for testing code. It allows you to create mock objects that simulate the behavior of real objects.
Example code
<?php
use PHPUnit\Framework\TestCase;
class MyTest extends TestCase
{
public function testSomething()
{
// Create a mock object of the class we want to test
$mock = $this->getMockBuilder('MyClass')
->setMethods(['doSomething'])
->getMock();
// Configure the mock object
$mock->expects($this->once())
->method('doSomething')
->will($this->returnValue('foo'));
// Run the test
$this->assertEquals('foo', $mock->doSomething());
}
}
Output example
OK (1 test, 1 assertion)
Code explanation
$mock = $this->getMockBuilder('MyClass')
- creates a mock object of the class we want to test.->setMethods(['doSomething'])
- sets the methods that should be mocked.->getMock()
- returns the mock object.$mock->expects($this->once())
- sets the expectation that the methoddoSomething
should be called once.->method('doSomething')
- specifies the method to be mocked.->will($this->returnValue('foo'))
- sets the return value of the mocked method.$this->assertEquals('foo', $mock->doSomething())
- runs the test and checks that the return value of the mocked method isfoo
.
Helpful links
More of Phpunit
- How to skip a PHPUnit test?
- How to run tests in parallel with PHPUnit?
- How to use hooks in PHPUnit?
- What are PHPUnit required extensions
- How to use the PHPUnit Framework TestCase?
- How to run PHPUnit in quiet mode?
- How to show warnings in PHPUnit?
- How to load fixtures with PHPUnit?
- How to use a listener with PHPUnit?
- How to stop PHPUnit on failure?
See more codes...