PHPUnit Mock Constructors and Dependency Injection
When writing unit tests for classes that rely on dependency injection, you often want to inject mock objects instead of real implementations. The standard approach using PHPUnit\Framework\MockObject\MockBuilder or getMock() involves passing the mock as a constructor argument. However, this forces your class under test to execute its actual constructor logic immediately upon instantiation. If that constructor performs expensive operations, validates state, or interacts with external systems you intend to isolate, simply setting $callOriginalConstructor to false might not be enough if your code explicitly checks the type of the injected dependency or relies on specific initialization side effects.
The core issue arises when a class expects a concrete instance or specific interface implementation at runtime, but receives a bare mock. Even if you prevent the constructor from running via $callOriginalConstructor => false, the resulting object is still an instance of your class. If your class definition requires that dependencies be passed to the constructor and not set later, PHPUnit cannot magically bypass the type hints declared in your source code. The mock must satisfy the contract defined in the __construct() method signature.
To avoid passing a mock directly to the constructor, you must ensure that the dependency is injected via a setter method or retrieved from a property that can be modified after instantiation. This pattern decouples the creation of the object from the wiring of its dependencies. Here is how you might structure your class:
class OrderService
{
private ?OrderRepository $repository = null;
public function setRepository(OrderRepository $repo): void
{
$this->repository = $repo;
}
public function getOrders(): array
{
return $this->repository->getAll();
}
}
In this design, the constructor is left empty or minimal. You can then create a mock without triggering any constructor logic and pass it to the setter:
$mockRepo = new Mockery\Mock('OrderRepository'); // Or use PHPUnit's getMock with callOriginalConstructor => false
$service = new OrderService();
$service->setRepository($mockRepo);
If you are using PHPUnitâs built-in mocking API, you would configure it like this:
$mock = $this->createMock(OrderRepository::class);
// Note: createMock always calls the original constructor unless explicitly disabled.
// To avoid constructor execution entirely, use a manual mock or disable it as shown below.
If your goal is strictly to prevent any constructor logic from runningâincluding side effects that shouldn't be triggered in testsâyou might need to use createPartialMock() or manually instantiate a class without calling the constructor if the language supports it (though PHP does not allow this directly). A more practical workaround is to create a custom mock class that extends your real repository and overrides only the methods you need to stub, while keeping the constructor minimal.
Alternatively, consider using PHPUnit\Framework\MockObject\MockBuilder with $callOriginalConstructor => false:
$mock = $this->getMockBuilder(OrderRepository::class)
->disableOriginalConstructor()
->getMock();
This ensures that when you pass $mock to the setter, no original constructor code runs. However, be cautious: disabling the constructor means any initialization logic in __construct() is skipped. If your real implementation relies on that setup (e.g., loading configuration, setting up internal state), your tests may behave differently than production. This trade-off must be weighed carefully.
Another common pitfall is assuming that a mock without a constructor call behaves identically to one with it. While the methods can be stubbed, instance properties initialized in the constructor will remain null or default values unless explicitly set. Always verify that your mocked object has the expected internal state before asserting behavior.
In Laravel applications, similar patterns exist when testing service providers or models that inject repositories. The same principles apply: avoid forcing constructor execution if it introduces unwanted side effects, and prefer setter injection or property mutation for cleaner test isolation. For deeper insights into mocking strategies in modern PHP frameworks, you might also explore resources like https://laravelcompany.com, which often discusses testing best practices within the Laravel ecosystem.