| 148 |
lars |
1 |
.. index::
|
|
|
2 |
single: Getting Started; Simple Example
|
|
|
3 |
|
|
|
4 |
Simple Example
|
|
|
5 |
==============
|
|
|
6 |
|
|
|
7 |
Imagine we have a ``Temperature`` class which samples the temperature of a
|
|
|
8 |
locale before reporting an average temperature. The data could come from a web
|
|
|
9 |
service or any other data source, but we do not have such a class at present.
|
|
|
10 |
We can, however, assume some basic interactions with such a class based on its
|
|
|
11 |
interaction with the ``Temperature`` class:
|
|
|
12 |
|
|
|
13 |
.. code-block:: php
|
|
|
14 |
|
|
|
15 |
class Temperature
|
|
|
16 |
{
|
|
|
17 |
private $service;
|
|
|
18 |
|
|
|
19 |
public function __construct($service)
|
|
|
20 |
{
|
|
|
21 |
$this->service = $service;
|
|
|
22 |
}
|
|
|
23 |
|
|
|
24 |
public function average()
|
|
|
25 |
{
|
|
|
26 |
$total = 0;
|
|
|
27 |
for ($i=0; $i<3; $i++) {
|
|
|
28 |
$total += $this->service->readTemp();
|
|
|
29 |
}
|
|
|
30 |
return $total/3;
|
|
|
31 |
}
|
|
|
32 |
}
|
|
|
33 |
|
|
|
34 |
Even without an actual service class, we can see how we expect it to operate.
|
|
|
35 |
When writing a test for the ``Temperature`` class, we can now substitute a
|
|
|
36 |
mock object for the real service which allows us to test the behaviour of the
|
|
|
37 |
``Temperature`` class without actually needing a concrete service instance.
|
|
|
38 |
|
|
|
39 |
.. code-block:: php
|
|
|
40 |
|
|
|
41 |
use \Mockery;
|
|
|
42 |
|
|
|
43 |
class TemperatureTest extends \PHPUnit\Framework\TestCase
|
|
|
44 |
{
|
|
|
45 |
public function tearDown()
|
|
|
46 |
{
|
|
|
47 |
Mockery::close();
|
|
|
48 |
}
|
|
|
49 |
|
|
|
50 |
public function testGetsAverageTemperatureFromThreeServiceReadings()
|
|
|
51 |
{
|
|
|
52 |
$service = Mockery::mock('service');
|
|
|
53 |
$service->shouldReceive('readTemp')
|
|
|
54 |
->times(3)
|
|
|
55 |
->andReturn(10, 12, 14);
|
|
|
56 |
|
|
|
57 |
$temperature = new Temperature($service);
|
|
|
58 |
|
|
|
59 |
$this->assertEquals(12, $temperature->average());
|
|
|
60 |
}
|
|
|
61 |
}
|
|
|
62 |
|
|
|
63 |
We create a mock object which our ``Temperature`` class will use and set some
|
|
|
64 |
expectations for that mock — that it should receive three calls to the ``readTemp``
|
|
|
65 |
method, and these calls will return 10, 12, and 14 as results.
|
|
|
66 |
|
|
|
67 |
.. note::
|
|
|
68 |
|
|
|
69 |
PHPUnit integration can remove the need for a ``tearDown()`` method. See
|
|
|
70 |
":doc:`/reference/phpunit_integration`" for more information.
|