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 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 mock a property in PHPUnit?
- How to increase memory limit in PHPUnit?
See more codes...