| 148 |
lars |
1 |
.. index::
|
|
|
2 |
single: Mockery; Gotchas
|
|
|
3 |
|
|
|
4 |
Gotchas!
|
|
|
5 |
========
|
|
|
6 |
|
|
|
7 |
Mocking objects in PHP has its limitations and gotchas. Some functionality
|
|
|
8 |
can't be mocked or can't be mocked YET! If you locate such a circumstance,
|
|
|
9 |
please please (pretty please with sugar on top) create a new issue on GitHub
|
|
|
10 |
so it can be documented and resolved where possible. Here is a list to note:
|
|
|
11 |
|
|
|
12 |
1. Classes containing public ``__wakeup()`` methods can be mocked but the
|
|
|
13 |
mocked ``__wakeup()`` method will perform no actions and cannot have
|
|
|
14 |
expectations set for it. This is necessary since Mockery must serialize and
|
|
|
15 |
unserialize objects to avoid some ``__construct()`` insanity and attempting
|
|
|
16 |
to mock a ``__wakeup()`` method as normal leads to a
|
|
|
17 |
``BadMethodCallException`` being thrown.
|
|
|
18 |
|
|
|
19 |
2. Mockery has two scenarios where real classes are replaced: Instance mocks
|
|
|
20 |
and alias mocks. Both will generate PHP fatal errors if the real class is
|
|
|
21 |
loaded, usually via a require or include statement. Only use these two mock
|
|
|
22 |
types where autoloading is in place and where classes are not explicitly
|
|
|
23 |
loaded on a per-file basis using ``require()``, ``require_once()``, etc.
|
|
|
24 |
|
|
|
25 |
3. Internal PHP classes are not entirely capable of being fully analysed using
|
|
|
26 |
``Reflection``. For example, ``Reflection`` cannot reveal details of
|
|
|
27 |
expected parameters to the methods of such internal classes. As a result,
|
|
|
28 |
there will be problems where a method parameter is defined to accept a
|
|
|
29 |
value by reference (Mockery cannot detect this condition and will assume a
|
|
|
30 |
pass by value on scalars and arrays). If references as internal class
|
|
|
31 |
method parameters are needed, you should use the
|
|
|
32 |
``\Mockery\Configuration::setInternalClassMethodParamMap()`` method.
|
|
|
33 |
Note, however that internal class parameter overriding is not available in
|
|
|
34 |
PHP 8 since incompatible signatures have been reclassified as fatal errors.
|
|
|
35 |
|
|
|
36 |
4. Creating a mock implementing a certain interface with incorrect case in the
|
|
|
37 |
interface name, and then creating a second mock implementing the same
|
|
|
38 |
interface, but this time with the correct case, will have undefined behavior
|
|
|
39 |
due to PHP's ``class_exists`` and related functions being case insensitive.
|
|
|
40 |
Using the ``::class`` keyword in PHP can help you avoid these mistakes.
|
|
|
41 |
|
|
|
42 |
The gotchas noted above are largely down to PHP's architecture and are assumed
|
|
|
43 |
to be unavoidable. But - if you figure out a solution (or a better one than
|
|
|
44 |
what may exist), let us know!
|