Blame | Letzte Änderung | Log anzeigen | RSS feed
.. index::single: Reference; Creating Test DoublesCreating Test Doubles=====================Mockery's main goal is to help us create test doubles. It can create stubs,mocks, and spies.Stubs and mocks are created the same. The difference between the two is that astub only returns a preset result when called, while a mock needs to haveexpectations set on the method calls it expects to receive.Spies are a type of test doubles that keep track of the calls they received, andallow us to inspect these calls after the fact.When creating a test double object, we can pass in an identifier as a name forour test double. If we pass it no identifier, the test double name will beunknown. Furthermore, the identifier does not have to be a class name. It is agood practice, and our recommendation, to always name the test doubles with thesame name as the underlying class we are creating test doubles for.If the identifier we use for our test double is a name of an existing class,the test double will inherit the type of the class (via inheritance), i.e. themock object will pass type hints or ``instanceof`` evaluations for the existingclass. This is useful when a test double must be of a specific type, to satisfythe expectations our code has.Stubs and mocks---------------Stubs and mocks are created by calling the ``\Mockery::mock()`` method. Thefollowing example shows how to create a stub, or a mock, object named "foo":.. code-block:: php$mock = \Mockery::mock('foo');The mock object created like this is the loosest form of mocks possible, and isan instance of ``\Mockery\MockInterface``... note::All test doubles created with Mockery are an instance of``\Mockery\MockInterface``, regardless are they a stub, mock or a spy.To create a stub or a mock object with no name, we can call the ``mock()``method with no parameters:.. code-block:: php$mock = \Mockery::mock();As we stated earlier, we don't recommend creating stub or mock objects withouta name.Classes, abstracts, interfaces^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^The recommended way to create a stub or a mock object is by using a name ofan existing class we want to create a test double of:.. code-block:: php$mock = \Mockery::mock('MyClass');This stub or mock object will have the type of ``MyClass``, through inheritance.Stub or mock objects can be based on any concrete class, abstract class or evenan interface. The primary purpose is to ensure the mock object inherits aspecific type for type hinting... code-block:: php$mock = \Mockery::mock('MyInterface');This stub or mock object will implement the ``MyInterface`` interface... note::Classes marked final, or classes that have methods marked final cannot bemocked fully. Mockery supports creating partial mocks for these cases.Partial mocks will be explained later in the documentation.Mockery also supports creating stub or mock objects based on a single existingclass, which must implement one or more interfaces. We can do this by providinga comma-separated list of the class and interfaces as the first argument to the``\Mockery::mock()`` method:.. code-block:: php$mock = \Mockery::mock('MyClass, MyInterface, OtherInterface');This stub or mock object will now be of type ``MyClass`` and implement the``MyInterface`` and ``OtherInterface`` interfaces... note::The class name doesn't need to be the first member of the list but it's afriendly convention to use for readability.We can tell a mock to implement the desired interfaces by passing the list ofinterfaces as the second argument:.. code-block:: php$mock = \Mockery::mock('MyClass', 'MyInterface, OtherInterface');For all intents and purposes, this is the same as the previous example.Spies-----The third type of test doubles Mockery supports are spies. The main differencebetween spies and mock objects is that with spies we verify the calls madeagainst our test double after the calls were made. We would use a spy when wedon't necessarily care about all of the calls that are going to be made to anobject.A spy will return ``null`` for all method calls it receives. It is not possibleto tell a spy what will be the return value of a method call. If we do that, thenwe would deal with a mock object, and not with a spy.We create a spy by calling the ``\Mockery::spy()`` method:.. code-block:: php$spy = \Mockery::spy('MyClass');Just as with stubs or mocks, we can tell Mockery to base a spy on any concreteor abstract class, or to implement any number of interfaces:.. code-block:: php$spy = \Mockery::spy('MyClass, MyInterface, OtherInterface');This spy will now be of type ``MyClass`` and implement the ``MyInterface`` and``OtherInterface`` interfaces... note::The ``\Mockery::spy()`` method call is actually a shorthand for calling``\Mockery::mock()->shouldIgnoreMissing()``. The ``shouldIgnoreMissing``method is a "behaviour modifier". We'll discuss them a bit later.Mocks vs. Spies---------------Let's try and illustrate the difference between mocks and spies with thefollowing example:.. code-block:: php$mock = \Mockery::mock('MyClass');$spy = \Mockery::spy('MyClass');$mock->shouldReceive('foo')->andReturn(42);$mockResult = $mock->foo();$spyResult = $spy->foo();$spy->shouldHaveReceived()->foo();var_dump($mockResult); // int(42)var_dump($spyResult); // nullAs we can see from this example, with a mock object we set the call expectationsbefore the call itself, and we get the return result we expect it to return.With a spy object on the other hand, we verify the call has happened after thefact. The return result of a method call against a spy is always ``null``.We also have a dedicated chapter to :doc:`spies` only... _creating-test-doubles-partial-test-doubles:Partial Test Doubles--------------------Partial doubles are useful when we want to stub out, set expectations for, orspy on *some* methods of a class, but run the actual code for other methods.We differentiate between three types of partial test doubles:* runtime partial test doubles,* generated partial test doubles, and* proxied partial test doubles.Runtime partial test doubles^^^^^^^^^^^^^^^^^^^^^^^^^^^^What we call a runtime partial, involves creating a test double and then tellingit to make itself partial. Any method calls that the double hasn't been told toallow or expect, will act as they would on a normal instance of the object... code-block:: phpclass Foo {function foo() { return 123; }function bar() { return $this->foo(); }}$foo = mock(Foo::class)->makePartial();$foo->foo(); // int(123);We can then tell the test double to allow or expect calls as with any otherMockery double... code-block:: php$foo->shouldReceive('foo')->andReturn(456);$foo->bar(); // int(456)See the cookbook entry on :doc:`../cookbook/big_parent_class` for an exampleusage of runtime partial test doubles.Generated partial test doubles^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^The second type of partial double we can create is what we call a generatedpartial. With generated partials, we specifically tell Mockery which methodswe want to be able to allow or expect calls to. All other methods will run theactual code *directly*, so stubs and expectations on these methods will notwork... code-block:: phpclass Foo {function foo() { return 123; }function bar() { return $this->foo(); }}$foo = mock("Foo[foo]");$foo->foo(); // error, no expectation set$foo->shouldReceive('foo')->andReturn(456);$foo->foo(); // int(456)// setting an expectation for this has no effect$foo->shouldReceive('bar')->andReturn(999);$foo->bar(); // int(456)It's also possible to specify explicitly which methods to run directly usingthe `!method` syntax:.. code-block:: phpclass Foo {function foo() { return 123; }function bar() { return $this->foo(); }}$foo = mock("Foo[!foo]");$foo->foo(); // int(123)$foo->bar(); // error, no expectation set.. note::Even though we support generated partial test doubles, we do not recommendusing them.One of the reasons why is because a generated partial will call the originalconstructor of the mocked class. This can have unwanted side-effects duringtesting application code.See :doc:`../cookbook/not_calling_the_constructor` for more details.Proxied partial test doubles^^^^^^^^^^^^^^^^^^^^^^^^^^^^A proxied partial mock is a partial of last resort. We may encounter a classwhich is simply not capable of being mocked because it has been marked asfinal. Similarly, we may find a class with methods marked as final. In such ascenario, we cannot simply extend the class and override methods to mock - weneed to get creative... code-block:: php$mock = \Mockery::mock(new MyClass);Yes, the new mock is a Proxy. It intercepts calls and reroutes them to theproxied object (which we construct and pass in) for methods which are notsubject to any expectations. Indirectly, this allows us to mock methodsmarked final since the Proxy is not subject to those limitations. The tradeoffshould be obvious - a proxied partial will fail any typehint checks for theclass being mocked since it cannot extend that class... _creating-test-doubles-aliasing:Aliasing--------Prefixing the valid name of a class (which is NOT currently loaded) with"alias:" will generate an "alias mock". Alias mocks create a class alias withthe given classname to stdClass and are generally used to enable the mockingof public static methods. Expectations set on the new mock object which referto static methods will be used by all static calls to this class... code-block:: php$mock = \Mockery::mock('alias:MyClass');.. note::Even though aliasing classes is supported, we do not recommend it.Overloading-----------Prefixing the valid name of a class (which is NOT currently loaded) with"overload:" will generate an alias mock (as with "alias:") except that creatednew instances of that class will import any expectations set on the originmock (``$mock``). The origin mock is never verified since it's used anexpectation store for new instances. For this purpose we use the term "instancemock" to differentiate it from the simpler "alias mock".In other words, an instance mock will "intercept" when a new instance of themocked class is created, then the mock will be used instead. This is usefulespecially when mocking hard dependencies which will be discussed later... code-block:: php$mock = \Mockery::mock('overload:MyClass');.. note::Using alias/instance mocks across more than one test will generate a fatalerror since we can't have two classes of the same name. To avoid this,run each test of this kind in a separate PHP process (which is supportedout of the box by both PHPUnit and PHPT)... _creating-test-doubles-named-mocks:Named Mocks-----------The ``namedMock()`` method will generate a class called by the first argument,so in this example ``MyClassName``. The rest of the arguments are treated in thesame way as the ``mock`` method:.. code-block:: php$mock = \Mockery::namedMock('MyClassName', 'DateTime');This example would create a class called ``MyClassName`` that extends``DateTime``.Named mocks are quite an edge case, but they can be useful when code dependson the ``__CLASS__`` magic constant, or when we need two derivatives of anabstract type, that are actually different classes.See the cookbook entry on :doc:`../cookbook/class_constants` for an exampleusage of named mocks... note::We can only create a named mock once, any subsequent calls to``namedMock``, with different arguments are likely to cause exceptions... _creating-test-doubles-constructor-arguments:Constructor Arguments---------------------Sometimes the mocked class has required constructor arguments. We can pass theseto Mockery as an indexed array, as the 2nd argument:.. code-block:: php$mock = \Mockery::mock('MyClass', [$constructorArg1, $constructorArg2]);or if we need the ``MyClass`` to implement an interface as well, as the 3rdargument:.. code-block:: php$mock = \Mockery::mock('MyClass', 'MyInterface', [$constructorArg1, $constructorArg2]);Mockery now knows to pass in ``$constructorArg1`` and ``$constructorArg2`` asarguments to the constructor... _creating-test-doubles-behavior-modifiers:Behavior Modifiers------------------When creating a mock object, we may wish to use some commonly preferredbehaviours that are not the default in Mockery.The use of the ``shouldIgnoreMissing()`` behaviour modifier will label thismock object as a Passive Mock:.. code-block:: php\Mockery::mock('MyClass')->shouldIgnoreMissing();In such a mock object, calls to methods which are not covered by expectationswill return ``null`` instead of the usual error about there being no expectationmatching the call.On PHP >= 7.0.0, methods with missing expectations that have a return typewill return either a mock of the object (if return type is a class) or a"falsy" primitive value, e.g. empty string, empty array, zero for ints andfloats, false for bools, or empty closures.On PHP >= 7.1.0, methods with missing expectations and nullable return typewill return null.We can optionally prefer to return an object of type ``\Mockery\Undefined``(i.e. a ``null`` object) (which was the 0.7.2 behaviour) by using anadditional modifier:.. code-block:: php\Mockery::mock('MyClass')->shouldIgnoreMissing()->asUndefined();The returned object is nothing more than a placeholder so if, by some act offate, it's erroneously used somewhere it shouldn't it will likely not pass alogic check.We have encountered the ``makePartial()`` method before, as it is the method weuse to create runtime partial test doubles:.. code-block:: php\Mockery::mock('MyClass')->makePartial();This form of mock object will defer all methods not subject to an expectation tothe parent class of the mock, i.e. ``MyClass``. Whereas the previous``shouldIgnoreMissing()`` returned ``null``, this behaviour simply calls theparent's matching method.