Test doubles are objects that mimic real objects in your application to remove dependencies on external resources like databases, APIs, or file systems. PHPUnit provides several test doubles, including mocks, stubs, and fakes.
Mocks allow you to simulate object behavior and verify interactions.
<?php use PHPUnit\Framework\TestCase; class UserServiceTest extends TestCase { public function testUserIsSaved() { $userRepository = $this->createMock(UserRepository::class); $userRepository->expects($this->once()) ->method('save') ->with($this->isInstanceOf(User::class)); $userService = new UserService($userRepository); $userService->registerUser("John Doe"); } }
Dependency injection (DI) allows objects to receive their dependencies from external sources rather than creating them internally. This improves code flexibility and testability.
<?php class UserService { private $repository; public function __construct(UserRepository $repository) { $this->repository = $repository; } }
When writing tests, you can inject mock dependencies:
$userRepositoryMock = $this->createMock(UserRepository::class); $userService = new UserService($userRepositoryMock);
Object interaction testing ensures that dependencies are used correctly within a class. PHPUnit allows verification of method calls, parameters, and execution count.
<?php use PHPUnit\Framework\TestCase; class PaymentServiceTest extends TestCase { public function testProcessPaymentCallsGateway() { $gateway = $this->createMock(PaymentGateway::class); $gateway->expects($this->once()) ->method('charge') ->with(100); $paymentService = new PaymentService($gateway); $paymentService->processPayment(100); } }
Follow the link to learn more about test doubles and mock objects: https://docs.phpunit.de/en/10.5/test-doubles.html#creating-mock-objects
This part covered test doubles, dependency injection, and verifying object interactions in PHPUnit. These techniques help create isolated, efficient, and maintainable tests. In the next part, we'll dive into handling exceptions and edge cases in PHPUnit tests.