Skip to content

Deferred class cannot be mocked #279

Backlog

Description

@downsider

The Deferred class uses the final keyword to prevent it from being extended by other developers. This creates a problem when testing code that uses Deferred, as it is impossible to mock the class, leading to situations where actual promises need to be resolved or rejected in tests that would otherwise entirely control the behaviour of the unit-under-test.

I have proposed a solution in PR #278, to create an interface for the Deferred class, but felt I should raise this as an issue, both for documentation and to allow for further discussion.

Activity

  1. clue commented on Nov 27, 2026

    @clue
    Member

    @downsider Thanks for raising this and for filing #278 along with it!

    Making Deferred final was a deliberate design decision, and so far I'm not sure an interface is needed for testing. As far as I can tell, tests can simply use a real Deferred instance: it's a plain in-memory object without any I/O, so the test still decides when and how things settle, for example:

    $deferred = new React\Promise\Deferred();
    
    $client = $this->createMock(Client::class);
    $client->method('fetch')->willReturn($deferred->promise());
    
    $service = new Service($client);
    $service->load();
    
    $deferred->resolve('value'); // or $deferred->reject(new RuntimeException('test'));

    The same works with React\Promise\resolve() and React\Promise\reject(). If the code under test creates its own Deferred internally, an interface wouldn't help either, as that new Deferred() can't be swapped out. This is different from something like ResolverInterface (reactphp/dns#139), which exists because a resolver performs actual network I/O.

    For alternative implementations, PromiseInterface is the abstraction consumers should type against. Classes are final to encourage composition over inheritance (#80), and for v3 we removed the PromisorInterface in #220 to reduce the API surface. So I'm hesitant about a new DeferredInterface, as it would go the opposite way and any future change to it would become a BC break for every implementation.

    That said, I may well be missing a use case here. Do you have a concrete example where a real Deferred doesn't work for you? Happy to reconsider once we see what this looks like in practice.

  2. added and removed on Nov 27, 2026
  3. downsider commented on Nov 27, 2026

    @downsider
    Author

    So this is coming from a position of upgrading from v2 to v3, where Deferred isn't final.

    I understand final is a design choice and it's your prerogative to decide that. However I would say that the decision has made the use of Deferred restrictive; I have to use your implementation, the only other option is to roll my own version of it, which I would not want to do. Having your implementation follow an interface would remove that restriction, without impacting existing usage for anyone else.

    The underlying issue is part principle and part pragmatism. My company use SOLID principles extensively, so we avoid tight coupling and inject dependencies in all our code. This makes replacing dependencies with mocks and controlling test behaviour very simple and isolates the code so that we're only ever running code from the unit-under-test.
    If we have to use concrete instances as you suggest, it means that in addition to running code from this library as part of the test, we can no longer control the result of calls to the instance's methods; e.g. we get an actual Promise instance back from Deferred::getPromise() instead of a mocked PromiseInterface, which chains onwards as we now don't control what the promise does either.

    From the pragmatic side, updating our test suite to account for real instances would be significantly more disruptive than the change I'm proposing.
    Currently we don't have to resolve promises in tests or worry about side effects in promise chains that the code sets up, making our tests small and isolated. Using real instances means we have to account for all dependencies used in a chain because we can no longer target just the bit that we need.

    Regarding backwards compatibility for an interface, I concede your point; changes to it would mean existing implementations would no longer meet the interface. It's not an ideal solution, but while the class is final, it looks to me to be the best option. It can be tempered a little by noting that the signature for Deferred only seems to change for new PHP syntax or deprecations, for which implementers could reasonably expect a breaking change, but your point stands.

    As a convoluted example to demonstrate the problem:

    class MyService {
    
      // using the old PromisorInterface from v2
      protected PromisorInterface $deferred
    
      public function __construct(
        protected PromisorFactory $promisorFactory,
        protected Api $api,
        protected Database $database
      ) {}
    
      public function initialisePromisor(): PromisorInterface
      {
        // We use factories for thing like this. The "new" keyword creates hard coupling
        $this->deferred = $this->promisorFactory->create(); 
        $this->deferred->getPromise()->catch(
          function () {
            // side effects as a demonstration, we wouldn't actually do things this way
            // the point is that we could be doing anything in here
            $data = $this->api->getData();
            $this->database->insert($data);
          }
        );
        return $this->deferred;
      }
    
      public function handleError(\Throwable $e): void
      {
        // do error handling logic, log the error, record metrics, etc...
        // and then ...
        $this->deferred?->reject($e);
      }
    
    }

    Unit test:

    class MyServiceTest extends TestCase
    {
    
      protected PromisorFactory|MockInterface $factory;
      protected PromisorInterface|MockInterface $promisor;
    
      public function setUp(): void
      {
        $this->promisor = \Mockery::mock(PromisorInterface::class);
        $this->factory = \Mockery:mock(PromisorFactory::class);
        $this->factory->shouldReceive("create")->andReturn($this->promisor);
      }
    
      public function testErrorHandlingRejectsPromise()
      {
        $e = new \Exception();
    
        $this->promisor->shouldReceive("getPromise->catch")->andReturn(\Mockery::mock(PromiseInterface::class)); 
        $this->promisor->shouldReceive("reject")->with($e)->once(); // this is the target, the behaviour we want to test
    
        // note that we don't have to set up expectations on the Api or Database mocks
        $service = new MyService($this->factory, \Mockery::mock(Api::class), \Mockery::mock(Database::class));
        $service->initialisePromisor();
        $service->handleError($e);
      }
    }

    The purpose of the testErrorHandlingRejectsPromise test is to ensure that Deferred::reject() is called and passed the correct exception. For this test we don't care if the api is called or it's data passed to the database, so we don't set any of that up. If we had to use an actual Deferred instance, that code would be executed when we reject, making the test surface a lot bigger.

    While this example isn't a real world scenario in itself and is rather simplistic, we do have more complex code that is tested in this way. Additionally, using mocks, we can intercept the callbacks passed to Promise methods and test them individually, without having to actually resolve or reject a promise, though this is an edge case.

    I hope this clarifies the issue. Please let me know what your thoughts are.

    P.S. Apologies for the wall of text. There was a lot to explain

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions