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; Not Calling the Original Constructor
3
 
4
Not Calling the Original Constructor
5
====================================
6
 
7
When creating generated partial test doubles, Mockery mocks out only the method
8
which we specifically told it to. This means that the original constructor of
9
the class we are mocking will be called.
10
 
11
In some cases this is not a desired behavior, as the constructor might issue
12
calls to other methods, or other object collaborators, and as such, can create
13
undesired side-effects in the application's environment when running the tests.
14
 
15
If this happens, we need to use runtime partial test doubles, as they don't
16
call the original constructor.
17
 
18
.. code-block:: php
19
 
20
    class MyClass
21
    {
22
        public function __construct()
23
        {
24
            echo "Original constructor called." . PHP_EOL;
25
            // Other side-effects can happen...
26
        }
27
    }
28
 
29
    // This will print "Original constructor called."
30
    $mock = \Mockery::mock('MyClass[foo]');
31
 
32
A better approach is to use runtime partial doubles:
33
 
34
.. code-block:: php
35
 
36
    class MyClass
37
    {
38
        public function __construct()
39
        {
40
            echo "Original constructor called." . PHP_EOL;
41
            // Other side-effects can happen...
42
        }
43
    }
44
 
45
    // This will not print anything
46
    $mock = \Mockery::mock('MyClass')->makePartial();
47
    $mock->shouldReceive('foo');
48
 
49
This is one of the reason why we don't recommend using generated partial test
50
doubles, but if possible, always use the runtime partials.
51
 
52
Read more about :ref:`creating-test-doubles-partial-test-doubles`.
53
 
54
.. note::
55
 
56
    The way generated partial test doubles work, is a BC break. If you use a
57
    really old version of Mockery, it might behave in a way that the constructor
58
    is not being called for these generated partials. In the case if you upgrade
59
    to a more recent version of Mockery, you'll probably have to change your
60
    tests to use runtime partials, instead of generated ones.
61
 
62
    This change was introduced in early 2013, so it is highly unlikely that you
63
    are using a Mockery from before that, so this should not be an issue.