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 methoddoSomethingshould 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 run tests in parallel with PHPUnit?
- How to stop PHPUnit on failure?
- How to show warnings in PHPUnit?
- How to generate a JUnit report in PHPUnit?
- How to install PHPUnit from Packagist?
- How to use the PHPUnit Framework TestCase?
- How to skip a PHPUnit test?
- How to mock an interface in PHPUnit?
- How to mock a method with PHPUnit?
- How to mock a private method in PHPUnit?
See more codes...