Skip to content
PHP Logo

How can PHP developers effectively use PHPUnit mocking for unit testing?

PHPUnit mocking is a powerful tool for PHP developers to isolate the code being tested and simulate the behavior of dependencies. To effectively use PHPUnit mocking for unit testing, developers should create mock objects that mimic the behavior of external dependencies, set up expectations for method calls and return values, and verify that the expected interactions occurred during the test.

php
// Example of using PHPUnit mocking for unit testing

// Class to be tested
class Calculator
{
    public function add($a, $b)
    {
        return $a + $b;
    }
}

// Test class
class CalculatorTest extends \PHPUnit\Framework\TestCase
{
    public function testAdd()
    {
        // Create a mock object for the Calculator class
        $calculatorMock = $this->getMockBuilder(Calculator::class)
            ->getMock();

        // Set up expectations for the add method
        $calculatorMock->expects($this->once())
            ->method('add')
            ->with(2, 3)
            ->willReturn(5);

        // Instantiate the Calculator class with the mock object
        $calculator = new Calculator();

        // Call the add method
        $result = $calculator->add(2, 3);

        // Verify that the expected interactions occurred
        $this->assertEquals(5, $result);
    }
}