How can mocking be utilized in PHP unit testing to simulate API responses and avoid external dependencies?

To simulate API responses and avoid external dependencies in PHP unit testing, mocking can be utilized. Mocking allows us to create fake objects that mimic the behavior of real objects, such as API calls, without actually making those calls. By using mocking, we can control the responses our code receives during testing, making it easier to isolate and test specific parts of our code without relying on external services.

// Example of using PHPUnit's mocking capabilities to simulate API responses

use PHPUnit\Framework\TestCase;

class APIClientTest extends TestCase
{
    public function testGetUserData()
    {
        // Create a mock of the API client class
        $apiClientMock = $this->getMockBuilder(APIClient::class)
                              ->disableOriginalConstructor()
                              ->getMock();

        // Set up the expected response from the API
        $expectedResponse = ['id' => 1, 'name' => 'John Doe'];

        // Define the behavior of the mock object
        $apiClientMock->expects($this->once())
                      ->method('getUserData')
                      ->willReturn($expectedResponse);

        // Inject the mock object into the code being tested
        $userService = new UserService($apiClientMock);

        // Call the method being tested
        $userData = $userService->getUserData();

        // Assert that the method returned the expected data
        $this->assertEquals($expectedResponse, $userData);
    }
}