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