demeter_chains.rst 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. .. index::
  2. single: Mocking; Demeter Chains
  3. Mocking Demeter Chains And Fluent Interfaces
  4. ============================================
  5. Both of these terms refer to the growing practice of invoking statements
  6. similar to:
  7. .. code-block:: php
  8. $object->foo()->bar()->zebra()->alpha()->selfDestruct();
  9. The long chain of method calls isn't necessarily a bad thing, assuming they
  10. each link back to a local object the calling class knows. As a fun example,
  11. Mockery's long chains (after the first ``shouldReceive()`` method) all call to
  12. the same instance of ``\Mockery\Expectation``. However, sometimes this is not
  13. the case and the chain is constantly crossing object boundaries.
  14. In either case, mocking such a chain can be a horrible task. To make it easier
  15. Mockery supports demeter chain mocking. Essentially, we shortcut through the
  16. chain and return a defined value from the final call. For example, let's
  17. assume ``selfDestruct()`` returns the string "Ten!" to $object (an instance of
  18. ``CaptainsConsole``). Here's how we could mock it.
  19. .. code-block:: php
  20. $mock = \Mockery::mock('CaptainsConsole');
  21. $mock->shouldReceive('foo->bar->zebra->alpha->selfDestruct')->andReturn('Ten!');
  22. The above expectation can follow any previously seen format or expectation,
  23. except that the method name is simply the string of all expected chain calls
  24. separated by ``->``. Mockery will automatically setup the chain of expected
  25. calls with its final return values, regardless of whatever intermediary object
  26. might be used in the real implementation.
  27. Arguments to all members of the chain (except the final call) are ignored in
  28. this process.