PHPUnit Mock Objects and Static Methods

PHPUnit Mock Objects and Static Methods

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

PHPUnit Mock Objects and Static Methods

Testing static methods in a legacy Doctrine context presents an immediate conceptual hurdle. The standard PHPUnit approach relies on mocking dependencies to isolate units of code, but you cannot mock a static method call because there is no object instance to inject the mock into. When examining a class like Model_User, where create() instantiates itself and calls $newUser->fromArray(), the static nature of the entry point breaks the usual dependency injection pattern required for mocking.

The core issue lies in the architecture of the code itself. The method create($userData) acts as a factory, but it constructs the object internally using new self(). This hard-coded instantiation means PHPUnit has no hook to intercept the creation of $newUser or inject a mock instance before the logic proceeds to fromArray() and save().

Why Direct Mocking Fails

Attempting to use PHPUnit\Framework\MockObject\MockBuilder directly on this specific scenario will fail. You cannot say "mock a User" because the code being tested does not accept a User dependency; it creates one from scratch. The static method bypasses the constructor and any setter logic that might have been intended for testing isolation.

In modern PHP development, specifically within frameworks like Laravel, this pattern is often refactored to resolve exactly this problem. By converting the factory method into a class method or utilizing a dedicated repository service, you enable dependency injection. However, if you must test the existing Doctrine_Record static method without rewriting the production code, you face a trade-off between architectural cleanliness and testing feasibility.

The Stubbing Workaround

If refactoring is not an option, the practical solution in PHPUnit 10+ (or via legacy mocks with specific constraints) involves mocking the return value of the internal logic rather than the call itself. Since fromArray and save are methods on the internal $newUser instance, you cannot mock their execution directly from the static facade.

Instead, you must shift focus to verifying that the static method behaves as expected regarding side effects or return values. However, with Doctrine_Record, the side effect is persistence. If you are testing in a unit context without a database, save() will likely fail if not mocked, but you still cannot mock $newUser because it isn't passed in.

The most robust approach for this specific legacy pattern involves mocking the repository layer that uses this static method, not the method itself. If your application code calls Model_User::create(), you can mock the Model_User class entirely if it is an autoloader-registered alias, but often Doctrine models are loaded dynamically.

A more direct, albeit hacky, solution used in older PHP versions involved using PHPUnit\Framework\MockObject to create a mock of the specific record class and then forcing the static method to use that mock by patching the internal logic, which is generally discouraged.

Refactoring for Testability

The definitive fix is architectural. The pattern shown in your source material mixes business logic (create) with domain implementation details (instantiating self). To make this testable with mocks:

  1. Convert to a Constructor Argument: Change Model_User to accept an instance or change the calling code to instantiate the model first.
  2. Use a Repository Pattern: Move the create logic into a Service class. The service accepts a User entity as an argument (or builds it externally) rather than creating it internally via static magic.

If you cannot refactor, the only way to "mock" the internal calls is to ensure your test environment isolates the database layer. You can mock the Doctrine ORM's persistence mechanisms so that calling save() does not actually hit the DB but returns a boolean or throws no exception. This allows you to verify that create completes successfully without needing to mock the internal $newUser variable itself, which remains impossible due to the static instantiation barrier.

Ultimately, relying on static factories for complex domain objects creates tight coupling between your test suite and the database layer. The goal of unit testing is to verify logic in isolation. If Model_User::create() requires a real database connection to validate its success (unless mocked globally), you are technically performing integration testing disguised as a unit test.

Practical Implementation Strategy

When writing the test for this specific static method, skip mocking the internal calls and focus on the outcome. Use a transaction manager or rollback strategy to ensure no data persists between tests if save() is actually executed.

use PHPUnit\Framework\TestCase;

class Model_UserTest extends TestCase
{
    public function testCreateReturnsInstance(): void
    {
        $data = ['username' => 'test', 'password' => 'secret'];
        
        // In a legacy Doctrine setup, you might not be able to mock 
        // the internal object creation. Instead, ensure the DB layer 
        // is isolated or mocked globally if necessary.
        
        $user = Model_User::create($data);
        
        $this->assertNotNull($user);
    }
}

If you need to assert that fromArray was called with specific data, you must refactor the class to use a constructor or setter that can be mocked. The static method pattern inherently prevents verification of internal state changes on the created object unless you inspect the global state or database directly after execution. This limitation highlights why modern frameworks like Laravel discourage static model methods in favor of service classes and dependency injection.

Our network