Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
.. index::
2
    single: Cookbook; Big Parent Class
3
 
4
Big Parent Class
5
================
6
 
7
In some application code, especially older legacy code, we can come across some
8
classes that extend a "big parent class" - a parent class that knows and does
9
too much:
10
 
11
.. code-block:: php
12
 
13
    class BigParentClass
14
    {
15
        public function doesEverything()
16
        {
17
            // sets up database connections
18
            // writes to log files
19
        }
20
    }
21
 
22
    class ChildClass extends BigParentClass
23
    {
24
        public function doesOneThing()
25
        {
26
            // but calls on BigParentClass methods
27
            $result = $this->doesEverything();
28
            // does something with $result
29
            return $result;
30
        }
31
    }
32
 
33
We want to test our ``ChildClass`` and its ``doesOneThing`` method, but the
34
problem is that it calls on ``BigParentClass::doesEverything()``. One way to
35
handle this would be to mock out **all** of the dependencies ``BigParentClass``
36
has and needs, and then finally actually test our ``doesOneThing`` method. It's
37
an awful lot of work to do that.
38
 
39
What we can do, is to do something... unconventional. We can create a runtime
40
partial test double of the ``ChildClass`` itself and mock only the parent's
41
``doesEverything()`` method:
42
 
43
.. code-block:: php
44
 
45
    $childClass = \Mockery::mock('ChildClass')->makePartial();
46
    $childClass->shouldReceive('doesEverything')
47
        ->andReturn('some result from parent');
48
 
49
    $childClass->doesOneThing(); // string("some result from parent");
50
 
51
With this approach we mock out only the ``doesEverything()`` method, and all the
52
unmocked methods are called on the actual ``ChildClass`` instance.